如何将STDIN传递给node.jssubprocess

我正在使用包装节点的pandoc库。 但我不知道如何将STDIN传递给subprocess`execFile …

 var execFile = require('child_process').execFile; var optipng = require('pandoc-bin').path; // STDIN SHOULD GO HERE! execFile(optipng, ['--from=markdown', '--to=html'], function (err, stdout, stderr) { console.log(err); console.log(stdout); console.log(stderr); }); 

在CLI上它看起来像这样:

 echo "# Hello World" | pandoc -f markdown -t html 

更新1

试图让它与spawn一起工作:

 var cp = require('child_process'); var optipng = require('pandoc-bin').path; var child = cp.spawn(optipng, ['--from=markdown', '--to=html'], { stdio: [ 0, 'pipe', 'pipe' ] }); child.stdin.write('# HELLO'); // then what? 

spawn()一样, execFile()也返回一个具有stdin可写stream的ChildProcess实例。

作为使用write()和侦听data事件的替代方法,您可以创build可读stream , push()input数据,然后将其pipe()child.stdin

 var execFile = require('child_process').execFile; var stream = require('stream'); var optipng = require('pandoc-bin').path; var child = execFile(optipng, ['--from=markdown', '--to=html'], function (err, stdout, stderr) { console.log(err); console.log(stdout); console.log(stderr); }); var input = '# HELLO'; var stdinStream = new stream.Readable(); stdinStream.push(input); // Add data to the internal queue for users of the stream to consume stdinStream.push(null); // Signals the end of the stream (EOF) stdinStream.pipe(child.stdin); 

以下是我如何工作:

 var cp = require('child_process'); var optipng = require('pandoc-bin').path; //This is a path to a command var child = cp.spawn(optipng, ['--from=markdown', '--to=html']); //the array is the arguments child.stdin.write('# HELLO'); //my command takes a markdown string... child.stdout.on('data', function (data) { console.log('stdout: ' + data); }); child.stdin.end(); 

我不确定它可能使用STDINchild_process.execFile()基于这些文档和下面的摘录,看起来像它只提供给child_process.spawn()

child_process.execFile()函数与child_process.exec()类似,不同之处在于它不产生shell。 而是将指定的可执行文件直接作为一个新进程产生,使其比child_process.exec()稍有效率。