【问题标题】:Node.js: Writing a function to return spawn stdout as a stringNode.js:编写一个函数以将 spawn stdout 作为字符串返回
【发布时间】:2013-03-20 04:44:21
【问题描述】:

我试图将此函数的输出作为字符串返回,但它一直以未定义的形式返回。我哪里错了?

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

【问题讨论】:

    标签: node.js


    【解决方案1】:

    您的函数在command.on 语句之后立即返回。 close 事件的回调中的 return 语句无处返回。 return 属于事件回调,不属于run()

    console.log 呼叫而不是return result

    一般来说你应该这样写:

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

    【讨论】:

    • 谢谢!我将如何更改它以将函数输出到变量而不是 console.log?
    • 您应该对回调函数中的命令结果执行任何操作,只需将console.log 替换为真实代码即可。一切都是异步的,因此即使您尝试将结果值放入全局变量中,您也无法判断它何时可用。如果您真的想以非异步方式做某事,这可能会有所帮助:github.com/caolan/async#series。但是问问自己为什么要这样做。
    • 哇,我太傻了。正在解决我在child.stdout.on('data', data) 上的承诺,并想知道为什么我的输出不完整并被随机截断。如果您遇到该问题,请先将数据存储到一个变量中,该变量在您的 child.on('close') 事件中解决/拒绝,如本答案所示。谢谢@fuwaneko
    【解决方案2】:
    var spawn = require('child_process').spawn,
        command  = spawn('ls', ['/tmp/']);
    command.stdout.pipe(process.stdout);
    

    以下link与您的问题完全相同。

    【讨论】:

    • 聪明,但他可能想做更多,然后将结果打印到 process.stdout
    • 感谢您的回答。我如何将 stdout.pipe 存储到变量中?
    【解决方案3】:

    你总是可以将你的函数包装在一个 Promise 中并返回它。我发现比@fuwaneko 的回调解决方案更高效

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

    【讨论】:

    • 我在使用ping 命令时尝试了此解决方案,但没有成功。不过,@fuwaneko 的解决方案对我有用。
    【解决方案4】:

    干净的方法是使用async/await 所以试试这样:

    const spawn = require('child_process').spawnSync;
     
    try {
        const child = spawn(cmd)
        return { stdout: child.stdout.toString(), stderr: child.stderr.toString() }
    } catch (error) {
        console.log(error);
        return error
    }
    

    【讨论】:

    • async/await在哪里?
    • @srghma 在第一行代码中我需要 spawnSync 然后不需要使用 async/await
    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 2023-02-02
    • 1970-01-01
    • 2022-11-15
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多