Node.js:编写一个函数以将 spawn stdout 作为字符串返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15515549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:56:22  来源:igfitidea点击:

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

node.js

提问by Billions McMillions

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

回答by fuwaneko

Your function returns immediately after command.onstatement. The returnstatement in your callback for the closeevent is returned to nowhere. The returnbelongs to event callback, not to run().

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

Put console.logcall instead of return result.

console.logcall 而不是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) });

回答by Marcel

var spawn = require('child_process').spawn,
    command  = spawn('ls', ['/tmp/']);
command.stdout.pipe(process.stdout);

The following linkis exactly the same question as yours.

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

回答by Nelson Owalo

You can always wrap your function in a promise and return that. I find more efficient than @fuwaneko's callback solution

你总是可以将你的函数包装在一个 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) })
    })
}