Skip to content

Commit

Permalink
Merge pull request #11 from aju/master
Browse files Browse the repository at this point in the history
Use map-stream to transform streams - code refactor
  • Loading branch information
jhnns committed Aug 10, 2014
2 parents 7284a1d + acad689 commit 7de8c85
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 39 deletions.
50 changes: 12 additions & 38 deletions lib/forkStdout.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var os = require("os");
var util = require("util");
var ForkStream = require("fork-stream");
var Linerstream = require("linerstream");
var mapStream = require('map-stream');

var messageToNode = "message to node: ";

Expand All @@ -21,6 +22,9 @@ function forkStdout(stdout) {
var phridgeEndpoint;
var cleanStdoutEndpoint;

// We know that phantomjs messages to node are not binary
stdout.setEncoding("utf8");

fork = new ForkStream({
classifier: function (chunk, done) {
chunk = chunk
Expand All @@ -34,50 +38,20 @@ function forkStdout(stdout) {
.pipe(new Linerstream())
.pipe(fork);

fork.a.pipe(phridgeEndpoint = new CropPhridgePrefix());
fork.b.pipe(cleanStdoutEndpoint = new RestoreLineBreaks());
// Removes the 'message to node: '-prefix from every chunk.
phridgeEndpoint = fork.a.pipe(mapStream(function(data, cb){
cb(null, data.slice(messageToNode.length));
}));

// We know that phantomjs messages to node are not binary
phridgeEndpoint.setEncoding("utf8");
// We need to restore EOL-character in stdout stream
cleanStdoutEndpoint = fork.b.pipe(mapStream(function(data, cb){
cb(null, data + os.EOL);
}));

return {
phridge: phridgeEndpoint,
cleanStdout: cleanStdoutEndpoint
};
}

/**
* Appends an EOL-character to every chunk.
*
* @param options
* @constructor
* @private
*/
function RestoreLineBreaks(options) {
Transform.call(this, options);
}
util.inherits(RestoreLineBreaks, Transform);

RestoreLineBreaks.prototype._transform = function (chunk, enc, cb) {
this.push(chunk + os.EOL);
cb();
};

/**
* Removes the 'message to node: '-prefix from every chunk.
*
* @param options
* @constructor
* @private
*/
function CropPhridgePrefix(options) {
Transform.call(this, options);
}
util.inherits(CropPhridgePrefix, Transform);

CropPhridgePrefix.prototype._transform = function (chunk, enc, cb) {
this.push(chunk.slice(messageToNode.length));
cb();
};

module.exports = forkStdout;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"linerstream": "git://github.com/jhnns/linerstream.git#fix/on-windows",
"phantomjs": "^1.9.7-15",
"temp": "^0.8.0",
"when": "^3.4.2"
"when": "^3.4.2",
"map-stream": "^0.1.0"
},
"devDependencies": {
"chai": "^1.9.1",
Expand Down

0 comments on commit 7de8c85

Please sign in to comment.