node.js:使用systemcall将文件写入/ tmp目录时遇到问题
作为一个练习,我正尝试使用node.js中的systemcall将一个小文本文件写入/ tmp目录。 这是我的代码:
#!/bin/node var child_process = require("child_process"); var send = "Hello, world!"; child_process.exec('cat - > /tmp/test1', { input: send });
该文件实际上被创build; 但是,没有内容被放置在其中。 事情只是挂起。 有人可以告诉我我失踪了吗?
另外,我真的很想知道如何做到这一点同步。
感谢您的任何意见。
... doug
嗯,除非我忘了rtm,这段代码将永远不会工作。 cp.exec没有这样的input选项。
但是有一个stdio选项,会让我们打开这个孩子的预期stdio。
child_process.exec('cat - > /tmp/test1', { stdio: 'pipe' });
请参阅https://nodejs.org/api/child_process.html#child_process_options_stdio
stdio
不是string,它们是stream,我们可以结束/写/pipe/closures/推等
请参阅https://nodejs.org/api/stream.html
请注意,stdin是可写的,stdout / stderr是可读的。
为了编写cat
的stdin,你需要使用cp.stdin对象并调用它的end()方法。
child_process.exec('cat - > /tmp/test1', { stdio: 'pipe' }).stdin.end('hello world');
请注意,结束方法是一个写入,然后终止stream,这是要求猫退出。
为了确保工作正常,我们应该重构它,不要将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);
请注意,stream程是全球性的。
我终于得到了我原来的工作方式。 最大的绊脚石是知道同步方法仅在node.js的0.12版本(及更高版本)中可用。 这是我终于开始工作的代码:
#!/usr/local/n/versions/node/0.12.14/bin/node var child_process = require('child_process'); var send = "Hello, world!" child_process.execSync('cat - > /tmp/test1', { input : send }).toString();
感谢所有的帮助。
... doug