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
deltanovember
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
mihai
source
to share
You can either pipe the node console output a la "node foo.js> output.txt" or you can use the fs package to write the file
0
ControlAltDel
source
to share
echo
doesn't seem to block for stdin:
~$ echo "hello" | echo
~$
^ no way out there ...
So what you can try:
var cat = spawn('tee', ['temp.txt']);
cat.stdin.write("testing");
cat.stdin.end();
I don't know if this will be helpful for you.
0
d_inevitable
source
to share