在与 child"/>
在与 child
child_process::spawn(...)
并接受 stream
到 stdio。例如:{ stdio: [Stream /* hereby "child stream" */, 'inherit', 'inherit'] }
对 stdin
. 的流接口有约束
我想转换我的流程'
stdin
并将其通过管道传递给 child_process。我使用转换流转换我的内容。但是,子流需要既是TTY
又有后盾fd
,否则node.js不会接受。
例如:
// node + the os demand a filedescriptor (fd),
// so let's get one
this._stdinfd = await fs.open("foo", "w+");
// pretend we have a real transform operation here :)
const myTransform = new node_stream_1.Transform({
transform(chunk, encoding, callback) {
callback(null, chunk);
},
});
// process.stdin is a Socket... so to best emulate stdin, let's
// make our transform stream also pipe thru a Socket
const mySocket = new node_net_1.Socket({ fd: this._stdinfd.fd });
// ^ but node hates this :)
process.stdin.pipe(myTransform).pipe(mySocket);
const proc = child_process_1.default.spawn("tmux", {
stdio: [mySocket, "inherit", "inherit"],
});
这个和类似的变体失败了。我不清楚将所需图元拼接在一起的最佳方法。让我知道你的想法!
回答如下:使用“管道”而不是将流直接传递到 stdio 数组中:
spawn("cat", {
stdio: [
"pipe",
"inherit",
"inherit"
]
});
然后使用子对象返回的对象并访问索引 0 处的“stdin”:
transform.pipe(child.stdio[0]);
完整示例:
const { spawn } = require("child_process");
const { Transform } = require("stream");
const transform = new Transform({
transform(chunk, enc, cb) {
chunk = chunk.toString();
chunk = chunk.toUpperCase();
cb(null, chunk);
}
});
const child = spawn("cat", {
stdio: [
"pipe",
"inherit",
"inherit"
]
});
transform.pipe(child.stdio[0]);
transform.write("Hello World");
上面的示例简单地将转换可写输入转换为大写字符串并将其推入可读队列,该队列通过管道进入子进程标准输入。
更多推荐
在与 child
发布评论