如何获得child.stdin的fd?

时间:2019-07-10 16:38:18

标签: node.js

如何让fd中的child.stdinfs.writeSync/readSync'open'从未被解雇。

const { spawn } = require('child_process');
const child = spawn('cat');
const cmd = 'foo\n';
let buff = new Buffer.from(cmd);
// child.stdin.fd is undefined
child.stdin.write(buff);

// never gets called
child.stdin.on('open', function (fd) {
  fs.writeSync(fd, buff, 0, buff.length, null, err => {
    if (err) throw 'Could not send command: ' + err;
    console.log('Command succesfully sent');
  });
});

child.stdout.on('data', (chunk) => {
  // echo
  process.stdout.write(chunk.toString());
});

child.on('close', (code) => {
  console.log(`exited with code ${code}`);
});

1 个答案:

答案 0 :(得分:0)

可以通过fd访问child.stdin中的child.stdin._handle.fd。不知道是否建议这样做,但我在v0.12.10和v10.16.0中都进行了测试。