Node.js: Writing a function to return spawn stdout as a string

Issue

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'));

Solution

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) });

Answered By – fuwaneko

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.