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

后端 未结 3 1193
旧时难觅i
旧时难觅i 2020-12-13 14:04

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          


        
3条回答
  •  无人及你
    2020-12-13 14:35

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

提交回复
热议问题