How can I use '>' to redirect output in Node.js?
For example, suppose I want to replicate a simple command
echo testing > temp.txt
Here 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
+3
source to share
3 answers
You cannot pass the redirection character (>) as an argument to appear, as this is not a valid argument to the command. You can use exec
spawn instead, which executes any command line you pass in a separate shell, or use this approach:
var cat = spawn('echo', ['testing']);
cat.stdout.on('data', function(data) {
fs.writeFile('temp.txt', data, function (err) {
if (err) throw err;
});
});
+4
source to share