我正在使用一个为 Node 包装 pandoc
的库。但我不知道如何将 STDIN 传递给子进程 `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()
还返回 ChildProcess
具有 stdin
的实例可写流。
作为使用 write()
的替代方法并监听 data
事件,你可以创建一个 readable stream , push()
你的输入数据,然后是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);
关于node.js - 如何将 STDIN 传递给 node.js 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37685461/