Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Created May 9, 2014 16:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jasonrhodes/12bf05cea957c42a3095 to your computer and use it in GitHub Desktop.
Save jasonrhodes/12bf05cea957c42a3095 to your computer and use it in GitHub Desktop.
Simple stream example for modifying file contents in gulp plugins
var through = require("through2");
var exec = require("child_process").exec;
// through2 docs: https://github.com/rvagg/through2
module.exports = function (options) {
// Not necessary to accept options but nice in case you add them later
options = options || {};
// through2.obj(fn) is a convenience wrapper around through2({ objectMode: true }, fn)
return through.obj(function (file, enc, cb) {
// Always error if file is a stream since gulp doesn't support a stream of streams
if (file.isStream()) {
this.emit('error', new Error('Streaming not supported in gulp-php lib'));
return cb();
}
// Handle the file, process it somehow
exec("php " + file.path, function (error, stdout, stderr) {
// If there's an error, this stops gulp but it's not great, needs work
if (error) {
this.emit('error', error);
return cb(error);
}
// Change the contents of the file, if necessary (must be a Buffer)
file.contents = new Buffer(stdout, "utf8");
// Push the file back onto the stream queue (this was this.queue in through lib)
this.push(file);
// Call the passed cb so the stream continues on
cb();
// Bind here or else save off var that = this earlier
}.bind(this));
});
};
@jasonrhodes
Copy link
Author

If you don't need to modify the file, obviously you can make it even simpler by doing whatever you want with file.contents, then just this.push(file) and cb() when you're done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment