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
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.
You can always wrap your function in a promise and return that. I find more efficient than @fuwaneko's callback solution
function run(cmd) {
return new Promise((resolve, reject) => {
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) {
resolve(result)
})
command.on('error', function(err) { reject(err) })
})
}
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) });