简体   繁体   中英

nodejs windows exec promise pending

I am running exec to get id from computer hardware. I am trying to assign the id to the variable cpu_id so that i can use it later in my script in a http request param. When console log seems to always be outputting Promise { <pending> } instead of the captured id.

I have played around with wait and async but couldn't get things to operate the way they should. any help or pointers would be greatly appreciated.

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

Exec returns a Promise. Try using execSync :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM