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