문제

I am using node.js on windows and I want to create separate .js scripts that I can treat individually like executables, and pipe the stdout from one executable as the stdin to another executable, in a Unix-like fashion.

There is technically a "|" operator in Windows but in my experience it does not work well at all. I am trying to implement a custom approach in node.js. The syntax can be different, something like,

node combine "somescript 1" "someotherscript"

Where combine.js is the script which handles piping the output of "node somescript 1" to the input of "node someotherscript". Here is my attempt so far but I could use some assistance, I am fairly new to node.js,

 var child = require('child_process');

 var firstArgs = process.argv[2].split(' '); 

 var firstChild = child.spawn('node', firstArgs);

 var secondChild = child.spawn('node');

 firstChild.stdout.pipe(secondChild.stdin, { end: false });

 secondChild.stdout.pipe(process.stdout, { end: false }); 

 secondChild.on('exit', function (code) {
   process.exit(code);
 });

Thanks!

도움이 되었습니까?

해결책

What I would do is use Node.js Transform streams for your scripts, and use combine.js to require and pipe those streams, based on command line arguments.

Example:

// stream1.js
var Transform = require('stream').Transform;

var stream1 = new Transform();
stream1._transform = function(chunk, encoding, done) {
  this.push(chunk.toString() + 's1\r\n');
  done();
};

module.exports = stream1;

// stream2.js
var Transform = require('stream').Transform;

var stream2 = new Transform();
stream2._transform = function(chunk, encoding, done) {
  this.push(chunk.toString() + 's2\r\n');
  done();
};

module.exports = stream2;

// combine.js

var stream1 = require('./' + process.argv[2]);
var stream2 = require('./' + process.argv[3]);

process.stdin.pipe(stream1).pipe(stream2).pipe(process.stdout);

That way running:

> echo "hi" | node stream1 stream2

Should output:

hi
s1
s2
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top