我正在运行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);
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);