javascript - How can I use '>' to redirect output within Node.js? - Stack Overflow

For example suppose I wish to replicate the simple mandecho testing > temp.txtThis is what I have tr

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
Add a ment  | 

4 Answers 4

Reset to default 5

You 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744203885a4563008.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信