Created
May 9, 2014 16:36
-
-
Save jasonrhodes/12bf05cea957c42a3095 to your computer and use it in GitHub Desktop.
Simple stream example for modifying file contents in gulp plugins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)
andcb()
when you're done.