UNPKG

1.88 kBJavaScriptView Raw
1var Stream = require('stream')
2 , gutil = require('gulp-util')
3;
4
5const PLUGIN_NAME = 'gulp-streamify';
6
7// Plugin function
8function streamifyGulp(pluginStream) {
9
10 var stream = Stream.Transform({objectMode: true});
11
12 // Threat incoming files
13 stream._transform = function(file, unused, done) {
14 // When null just pass out
15 if(file.isNull()) {
16 stream.push(file); done();
17 return;
18 }
19 // When buffer pass through the plugin
20 if(file.isBuffer()) {
21 pluginStream.once('data', function(file) {
22 stream.push(file);
23 done();
24 });
25 pluginStream.write(file);
26 return;
27 }
28
29 // Wrap the stream
30 var originalStream = file.contents
31 , buf = new Buffer(0)
32 , bufstream = new Stream.Writable()
33 , newStream = new Stream.Readable()
34 ;
35
36 // Pending while no full buffer
37 newStream._read = function() {
38 newStream.push('');
39 };
40
41 // Buffer the stream
42 bufstream._write = function(chunk, encoding, cb) {
43 buf = Buffer.concat([buf, chunk], buf.length + chunk.length);
44 cb();
45 };
46
47 // When buffered
48 bufstream.on('finish', function() {
49 // Prepare to catch back the file
50 pluginStream.once('data', function(file) {
51 // Get the transformed buffer
52 buf = file.contents;
53 // Write the buffer only when datas are needed
54 newStream._read = function() {
55 // Write the content back to the stream
56 newStream.push(buf);
57 newStream.push(null);
58 };
59 // Pass the file out
60 file.contents = newStream;
61 stream.push(file);
62 done();
63 });
64 // Send the buffer wrapped in a file
65 file.contents = buf;
66 pluginStream.write(file);
67 });
68
69 originalStream.pipe(bufstream);
70
71 };
72
73 return stream;
74
75}
76
77// Export the plugin main function
78module.exports = streamifyGulp;
79