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

标签 node.js command-line-interface

我正在使用一个为 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/

相关文章:

javascript - 静态内容服务在 Express 中不起作用

javascript - 端点异步轮询

MySql CLI - 查询的别名/名称

php - 如何在 Mac 中同时执行 PHP CLI 脚本

.net - 将普通 char* 转换为 cli 数组

node.js - 在node-xmpp中检索名册

node.js - 具有异步操作的 Mongoose 游标

javascript - NodeJS 在 for 循环中的回调值是相同的

Java命令行工具,详细输出标志

linux - 处理将参数传递给嵌套脚本调用并创建有效的菜单驱动 cli 的最佳方法