如何将STDIN传递给node.js子进程

问题描述:

我正在使用为节点包装pandoc的库。但我无法弄清楚如何STDIN传递给子进程`的execfile ...如何将STDIN传递给node.js子进程

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? 

以下是我得到它的工作:

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(); 

我不知道它可以使用STDIN基于这些docs及以下摘录child_process.execFile(),看起来像它仅适用于child_process.spawn()

The child_process.execFile() function is similar to child_process.exec() except that it does not spawn a shell. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than child_process.exec().

+0

你能呈现怎样的STDIN使用通产卵? – emersonthis

+0

@emersonthis遵循我在答案中发布的文档链接,它显示了如何在代码片段中。 – peteb

+0

我实际上已经在那个页面上的最后一个小时,我不能得到它的工作... – emersonthis

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

作为替代使用write()并侦听data事件,你可以创建一个readable streampush()输入数据,然后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);