How can I use '>' to redirect output within Node.js?

Go To StackoverFlow.com

3

For example suppose I wish to replicate the simple command

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

2012-04-03 21:15
by deltanovember
Have you tried setting stdoutStream instead - Jim Schubert 2012-04-03 21:34


4

You cannot pass in the redirection character (>) as an argument to spawn, since it's not a valid argument to the command. You can either use exec instead of spawn, which executes whatever command 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;
    });
});
2012-04-03 21:43
by mihai


0

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

2012-04-03 21:19
by ControlAltDel
I think the op wants to run a commandline program and pipe into stdin - d_inevitable 2012-04-03 21:20


0

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.

2012-04-03 21:22
by d_inevitable
This is not writing any files when I tr - deltanovember 2012-04-03 21:29
Ok, sorry, I've updated my answer. It is not the '>' operator though that does the output to file now - d_inevitable 2012-04-03 21:36