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

admin2025-04-09  3

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744203886a235927.html

最新回复(0)