index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var defaults = require('defaults');
  3. var path = require('path');
  4. var through2 = require('through2');
  5. var mkdirp = require('mkdirp');
  6. var fs = require('graceful-fs');
  7. var writeContents = require('./writeContents');
  8. function dest(outFolder, opt) {
  9. opt = opt || {};
  10. if (typeof outFolder !== 'string' && typeof outFolder !== 'function') {
  11. throw new Error('Invalid output folder');
  12. }
  13. var options = defaults(opt, {
  14. cwd: process.cwd()
  15. });
  16. if (typeof options.mode === 'string') {
  17. options.mode = parseInt(options.mode, 8);
  18. }
  19. var cwd = path.resolve(options.cwd);
  20. function saveFile (file, enc, cb) {
  21. var basePath;
  22. if (typeof outFolder === 'string') {
  23. basePath = path.resolve(cwd, outFolder);
  24. }
  25. if (typeof outFolder === 'function') {
  26. basePath = path.resolve(cwd, outFolder(file));
  27. }
  28. var writePath = path.resolve(basePath, file.relative);
  29. var writeFolder = path.dirname(writePath);
  30. // wire up new properties
  31. file.stat = file.stat ? file.stat : new fs.Stats();
  32. file.stat.mode = (options.mode || file.stat.mode);
  33. file.cwd = cwd;
  34. file.base = basePath;
  35. file.path = writePath;
  36. // mkdirp the folder the file is going in
  37. mkdirp(writeFolder, function(err){
  38. if (err) {
  39. return cb(err);
  40. }
  41. writeContents(writePath, file, cb);
  42. });
  43. }
  44. var stream = through2.obj(saveFile);
  45. // TODO: option for either backpressure or lossy
  46. stream.resume();
  47. return stream;
  48. }
  49. module.exports = dest;