作为练习,我试图使用来自node.js的系统调用将一个小的文本文件写入/ tmp目录。这是我的代码:
#!/bin/node
var child_process = require("child_process");
var send = "Hello, world!";
child_process.exec('cat - > /tmp/test1', { input: send });
该文件实际上已创建;但是,其中没有内容。事情就挂了。有人可以告诉我我想念的吗?
另外,我真的很想知道如何同步执行此操作。
感谢您的任何投入。
... doug
除非我也忘记了rtm,否则此代码将永远无法工作。cp.exec没有此类输入选项。
但是有一个stdio选项,可以让我们在孩子身上打开预期的stdio。
child_process.exec('cat - > /tmp/test1', { stdio: 'pipe' });
参见https://nodejs.org/api/child_process.html#child_process_options_stdio
stdio
s不是字符串,而是流,我们可以结束/写入/管道/关闭/推送等
参见https://nodejs.org/api/stream.html
注意,stdin是可写的,stdout / stderr是可读的。
现在,要编写cat
您的标准输入,将使用cp.stdin对象并调用其end()方法。
child_process.exec('cat - > /tmp/test1', { stdio: 'pipe' }).stdin.end('hello world');
请注意,end方法是写操作,然后终止流,这是告诉cat退出所必需的。
为确保此方法正常运行,我们应该对其进行重构,以免将stdin发送到文件中,而是将child.stdout通过管道传递到process.stdout。
var child_process = require('child_process');
var cp = child_process.exec('cat -', { stdio: 'pipe' });
cp.stdin.end('hello world');
cp.stdout.pipe(process.stderr);
请注意,该过程是全局的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句