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

后端 未结 3 1174
旧时难觅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:28
    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.

    0 讨论(0)
  • 2020-12-13 14:28

    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) })
        })
    }
    
    0 讨论(0)
  • 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) });
    
    0 讨论(0)
提交回复
热议问题