admin管理员组文章数量:1400182
For example suppose I wish to replicate the simple mand
echo testing > temp.txt
This is what I have tried
var util = require('util'),
spawn = require('child_process').spawn;
var cat = spawn('echo', ['> temp.txt']);
cat.stdin.write("testing");
cat.stdin.end();
Unfortunately no success
For example suppose I wish to replicate the simple mand
echo testing > temp.txt
This is what I have tried
var util = require('util'),
spawn = require('child_process').spawn;
var cat = spawn('echo', ['> temp.txt']);
cat.stdin.write("testing");
cat.stdin.end();
Unfortunately no success
Share Improve this question asked Apr 3, 2012 at 21:15 deltanovemberdeltanovember 44.1k66 gold badges167 silver badges245 bronze badges 1- Have you tried setting stdoutStream instead? – Jim Schubert Commented Apr 3, 2012 at 21:34
4 Answers
Reset to default 5You cannot pass in the redirection character (>) as an argument to spawn, since it's not a valid argument to the mand.
You can either use exec
instead of spawn, which executes whatever mand string you give it in a separate shell, or take this approach:
var cat = spawn('echo', ['testing']);
cat.stdout.on('data', function(data) {
fs.writeFile('temp.txt', data, function (err) {
if (err) throw err;
});
});
You can either pipe node console output a la "node foo.js > output.txt" or you can use the fs package to do file writing
echo
doesn't seem to block for stdin:
~$ echo "hello" | echo
~$
^ no output there...
So what you could try is this:
var cat = spawn('tee', ['temp.txt']);
cat.stdin.write("testing");
cat.stdin.end();
I don't know if that would be useful to you though.
Use exec
.
const { exec } = require( "child_process" );
exec( "echo > temp.txt" );
Not sure what the pros/cons are between exec
and spawn
, but it does allow you to easily run the full mand and write it or append it to a file.
本文标签: javascriptHow can I use 39gt39 to redirect output within NodejsStack Overflow
版权声明:本文标题:javascript - How can I use '>' to redirect output within Node.js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744203884a2595093.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论