- 在创建窗口的
webPreferences
的配置项中开放node的api
- 在渲染进程导入node的
child_process
,关于child_process
的信息请移步官网.然后为了显示运行结果我们还需要进行转码,这里用到的是iconv-lite
包,下载完毕后按如下设置即可
const child_process = require("child_process");
const iconv = require("iconv-lite");
iconv.skipDecodeWarning = true;
const encodings = "cp936";
const binaryEncoding = "binary";
- 执行
ping
命令
const ip = 'www.baidu.com';
const child = child_process.exec(
"ping " + ip,
{ encoding: binaryEncoding },
(error, stdout, stderr) => {
if (error) {
console.log("ip is inactive.");
item.checked = false;
if (this.showCmd) {
Message.alert("该IP地址暂不可用!", "tip");
}
// this.msgList.push(iconv.decode(error, encodings));
// console.log(iconv.decode(error, encodings));
} else {
if (
this.msgList.some((item) => {
return item.indexOf("无法访问目标主机") != -1;
})
) {
item.checked = false;
if (this.showCmd) {
Message.alert("该IP地址暂不可用!", "tip");
}
} else {
console.log("ip is active.");
console.log(iconv.decode(stdout, encodings));
// console.log(iconv.decode(stderr, encodings));
item.checked = true;
if (this.showCmd) {
Message.alert("该IP地址可用!", "tip");
}
}
}
}
);
exec
的回调参数中的三个形参分别是运行命令出错的信息error
,标准输出stdout
,标准错误stderr
.
一般说来,普通的错误例如超时、找不到主机名都会被error拿到,但是无法访问目标主机这个错误是不会被error捕捉到的,它会在stdout
中。所以我这里用了一个蠢方法,就是分割判断是否有这个字符串,目前我不知道还有啥方法。
- 可能有的人想显示运行过程,而不是运行完毕后一次性打印,这里就需要对
stdout
和stderr
进行监听了
child.stdout.on("data", (data) => {
// console.log(iconv.decode(data, encodings));
this.msgList.push(iconv.decode(data, encodings));
});
child.stderr.on("data", (err) => {
item.checked = false;
// console.log("stderr 输出:", iconv.decode(err, encodings));
this.msgList.push(iconv.decode(err, encodings));
});