Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 217
deltanovember Avatar asked Apr 03 '12 21:04

deltanovember


1 Answers

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;
    });
});
like image 189
mihai Avatar answered Nov 16 '22 11:11

mihai