nodejs Windows执行承诺未完成

问题描述 投票:0回答:1

我正在运行exec以从计算机硬件获取ID。我试图将ID分配给变量cpu_id,以便以后可以在我的脚本中的http请求参数中使用它。当控制台日志似乎总是输出Promise { <pending> }而不是捕获的ID时。

我一直在等待和异步操作,但是无法使事情按应有的方式运行。任何帮助或指示,将不胜感激。

function get_cpu_id() {
    if (process.platform === "win32") {
        return execShellCommand('wmic csproduct get UUID /format:list').then(function(std){
            return std.replace(/\s/g, '').split("=")[1];
        });
    } else {
        return execShellCommand('cat /proc/cpuinfo | grep Serial').then(function(std){
            return std;
        });
    }
}

function execShellCommand(cmd) {
    const exec = require('child_process').exec;

    return new Promise((resolve, reject) => {
        exec(cmd, (error, stdout, stderr) => {
            if (error) {
                console.warn(error);
            }

            resolve(stdout ? stdout : stderr);
        });
    });
}

let cpu_id = get_cpu_id();

console.log(cpu_id);
javascript node.js promise exec
1个回答
0
投票

Exec返回一个承诺。使用execSync的TRy:

const execSync = require('child_process').execSync;

function get_cpu_id() {
    if (process.platform === "win32") {
        return execSync('wmic csproduct get UUID /format:list').toString();
    } else {
        return execSync('cat /proc/cpuinfo | grep Serial').toString();
    }
}


let cpu_id = get_cpu_id();

console.log(cpu_id);
© www.soinside.com 2019 - 2024. All rights reserved.