【问题标题】:Nodejs "child_process" spawn variable undefinedNodejs“child_process”生成变量未定义
【发布时间】:2020-04-06 19:18:45
【问题描述】:

我的功能:

    const { spawn } = require('child_process');
    const prc = spawn("free", []);

    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) {
                callback(result)
            });
            command.on('error', function(err) { reject(err) })

    }

    var t;
    run('ls', function (result) {
        t=result; 
        console.log(t); // It works
    });

    console.log(t); //undefined

console.log(t) 它可以正常工作并打印。

而函数外的console.log(t)返回未定义。

但要解决问题, 我需要使用 Promise 还是等待/异步?

谢谢。

【问题讨论】:

  • 您正试图在结果分配之前执行它(它正在异步运行)。

标签: node.js


【解决方案1】:

欢迎来到异步编程。 console.log(t); 实际上会在 run('ls', function (result) { t=result; console.log(t); // It works }); 之前运行

Promises 与 async/await 结合使用:

(async function() {
const { spawn } = require('child_process');
const prc = spawn("free", []);

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) {
            t = result
            resolve(result)
        });
        command.on('error', function(err) { reject(err) })
        }   
}

var t;
await run('ls');

console.log(t); //defined!
})()

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 2018-06-29
    • 2017-08-03
    • 2023-03-14
    • 2018-05-29
    • 1970-01-01
    • 2016-07-31
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多