I'm trying to return the output of this function as a string, but it keeps returning as undefined. Where am I going wrong?
function run(cmd){ var spawn = require('child_process').spawn; var command = spawn(cmd); var result = ''; command.stdout.on('data', function(data) { result += data.toString(); }); command.on('close', function(code) { return result; }); } console.log(run('ls'));
Your function returns immediately after command.on
statement. The return
statement in your callback for the close
event is returned to nowhere. The return
belongs to event callback, not to run()
.
Put console.log
call instead of return result
.
Generally speaking you should write something like:
function run(cmd, callback) { var spawn = require('child_process').spawn; var command = spawn(cmd); var result = ''; command.stdout.on('data', function(data) { result += data.toString(); }); command.on('close', function(code) { return callback(result); }); } run("ls", function(result) { console.log(result) });
var spawn = require('child_process').spawn, command = spawn('ls', ['/tmp/']); command.stdout.pipe(process.stdout);
The following link is exactly the same question as yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With