3 var os = require("os");
4 var util = require("util");
5 var ForkStream = require("fork-stream");
6 var Linerstream = require("linerstream");
7 var Transform = require("stream").Transform;
9 var messageToNode = "message to node: ";
12 * Creates a fork stream which pipes messages starting with 'message to node: ' to our phridge stream
13 * and any other message to the other stream. Thus console.log() inside PhantomJS is still printed to the
14 * console while using stdout as communication channel for phridge.
16 * @param {stream.Readable} stdout
17 * @returns {{phridge: stream.Readable, cleanStdout: stream.Readable}}
19 function forkStdout(stdout) {
22 var cleanStdoutEndpoint;
24 // Expecting a character stream because we're splitting messages by an EOL-character
25 stdout.setEncoding("utf8");
27 fork = new ForkStream({
28 classifier: function (chunk, done) {
30 .slice(0, messageToNode.length);
31 done(null, chunk === messageToNode);
36 .pipe(new Linerstream())
39 // Removes the 'message to node: '-prefix from every chunk.
40 phridgeEndpoint = fork.a.pipe(new CropPhridgePrefix({
44 // We need to restore EOL-character in stdout stream
45 cleanStdoutEndpoint = fork.b.pipe(new RestoreLineBreaks({
50 phridge: phridgeEndpoint,
51 cleanStdout: cleanStdoutEndpoint
56 * Appends an EOL-character to every chunk.
58 * @param {Object} options stream options
62 function RestoreLineBreaks(options) {
63 Transform.call(this, options);
65 util.inherits(RestoreLineBreaks, Transform);
67 RestoreLineBreaks.prototype._transform = function (chunk, enc, cb) {
68 this.push(chunk + os.EOL);
73 * Removes the 'message to node: '-prefix from every chunk.
75 * @param {Object} options stream options
79 function CropPhridgePrefix(options) {
80 Transform.call(this, options);
82 util.inherits(CropPhridgePrefix, Transform);
84 CropPhridgePrefix.prototype._transform = function (chunk, enc, cb) {
85 this.push(chunk.slice(messageToNode.length));
89 module.exports = forkStdout;