deltanovember
deltanovember

Reputation: 44061

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

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

Upvotes: 5

Views: 3822

Answers (4)

Joshua Pinter
Joshua Pinter

Reputation: 47581

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 command and write it or append it to a file.

Upvotes: 0

mihai
mihai

Reputation: 38573

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;
    });
});

Upvotes: 5

d_inevitable
d_inevitable

Reputation: 4461

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.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35096

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

Upvotes: 0

Related Questions