index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*!
  2. * output-file-sync | MIT (c) Shinnosuke Watanabe
  3. * https://github.com/shinnn/output-file-sync
  4. */
  5. 'use strict';
  6. var dirname = require('path').dirname;
  7. var writeFileSync = require('graceful-fs').writeFileSync;
  8. var inspect = require('util').inspect;
  9. var objectAssign = require('object-assign');
  10. var mkdirpSync = require('mkdirp').sync;
  11. module.exports = function outputFileSync(filePath, data, options) {
  12. if (typeof filePath !== 'string') {
  13. throw new TypeError(
  14. inspect(filePath) +
  15. ' is not a string. Expected a file path to write a file.'
  16. );
  17. }
  18. if (filePath === '') {
  19. throw new Error('Expected a file path to write a file, but received an empty string instead.');
  20. }
  21. options = options || {};
  22. var mkdirpOptions;
  23. if (typeof options === 'string') {
  24. mkdirpOptions = null;
  25. } else if (options.dirMode) {
  26. mkdirpOptions = objectAssign({}, options, {mode: options.dirMode});
  27. } else {
  28. mkdirpOptions = options;
  29. }
  30. var writeFileOptions;
  31. if (options.fileMode) {
  32. writeFileOptions = objectAssign({}, options, {mode: options.fileMode});
  33. } else {
  34. writeFileOptions = options;
  35. }
  36. var createdDirPath = mkdirpSync(dirname(filePath), mkdirpOptions);
  37. writeFileSync(filePath, data, writeFileOptions);
  38. return createdDirPath;
  39. };