UNPKG

2.03 kBJavaScriptView Raw
1var through = require('through');
2var path = require('path');
3var gutil = require('gulp-util');
4var File = gutil.File;
5var PluginError = gutil.PluginError;
6
7function concatFilenames(filename, opts) {
8 'use strict';
9
10 var error = {
11 noFilename: 'Missing fileName option for gulp-concat-filenames',
12 noStreaming: 'Streaming not supported'
13 };
14
15 opts = opts || {};
16
17 if (!filename) {
18 throw new PluginError('gulp-concat-filenames', error.noFilename);
19 }
20
21 if (typeof opts.newLine !== 'string') {
22 opts.newLine = gutil.linefeed;
23 }
24
25 var buffer = [],
26 firstfile;
27
28 function bufferContents(file) {
29 if (file.isNull()) {
30 return;
31 }
32
33 if (file.isStream()) {
34 var errorNoStream = new PluginError('gulp-concat-filenames', error.noStreaming);
35 return this.emit('error', errorNoStream);
36 }
37
38 firstfile = firstfile || file;
39
40 var requirePath = path.resolve(file.path);
41
42
43 requirePath = opts.root ?
44 path.relative(opts.root, requirePath) :
45 requirePath;
46
47 var thisRequire = [
48 opts.prepend || '',
49 requirePath.replace(/\\/g, '\/'),
50 opts.append || '',
51 opts.newLine
52 ].join('');
53
54 buffer.push(new Buffer(thisRequire));
55 }
56
57 function endStream() {
58 if (buffer.length === 0) {
59 return this.emit('end');
60 }
61
62 var outFileContents = Buffer.concat(buffer),
63 outFilePath = path.join(firstfile.base, filename);
64
65 var outFile = new File({
66 cwd: firstfile.cwd,
67 base: firstfile.base,
68 path: outFilePath,
69 contents: outFileContents
70 });
71
72 this.emit('data', outFile);
73 this.emit('end');
74 }
75
76 return through(bufferContents, endStream);
77}
78
79module.exports = concatFilenames;
\No newline at end of file