admin 管理员组文章数量: 1184232
如何将 STDIN 传递给 node.js 子进程
我正在使用一个为节点包装
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事件的替代方法,您可以创建一个可读流,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);
本文标签: 如何将 STDIN 传递给 nodejs 子进程
版权声明:本文标题:如何将 STDIN 传递给 node.js 子进程 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.roclinux.cn/b/1717563354a708823.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论