最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin24浏览0评论

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

如何将 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);
发布评论

评论列表(0)

  1. 暂无评论