javascript - 杀死子进程执行
问题描述
我需要你的帮助。我想通过 ifconfig.me 获取我的 Beaglebone 的公共 IP 地址。
如果我有一个现有的互联网连接,它工作正常。如果我没有互联网连接,则应中止请求。这是我的代码:
function publicIP_www(callback){
try{
exec('curl ifconfig.me',{timeout:3000}, function(error, stdout, stderr){
callback(stdout); });
}
catch (err){
callback("000.000.000.000");
}
}
返回的 IP 地址随后会显示在浏览器中的网站上。如果没有互联网连接,浏览器将永远计算。似乎 call exec ...... 没有终止。
我期待您的支持,并希望有人能告诉我我做错了什么。
最好的问候汉斯
解决方案
由于无法看到您的代码,很难预测为什么它在您的情况下不起作用。但是您可以尝试下一个效果很好的方法。当然它很脏,只是一个例子。
下一个代码用于“Node.js Express App + Jade”项目的 index.js 文件,该项目是从 WebStorm IDE 中的模板创建的。
const util = require('util');
const exec = util.promisify(require('child_process').exec);
....
....
router.get('/', async function(req, res, next) {
try {
const {stdout, stderr} = await exec('curl ifconfig.me');
res.render('index', { title: stdout});
}
catch (err) {
res.render('index',{ title: "000.000.000.000"});
}
});
或使用
const util = require('util');
const exec = require('child_process').exec;
function publicIP_www(callback){
exec('curl ifconfig.me',{timeout:3000}, function(error, stdout, stderr){
if (error) {
return callback("000.000.000.000");
}
callback(stdout);
});
}
router.get('/', function(req, res, next) {
publicIP_www((title) => {
res.render('index', { title });
})
});
推荐阅读
- google-sheets - 如何将单元格组合成两列以显示同一行中元素之间的所有链接
- tarantool - 在哪里可以找到用于对其执行远程调用的 vshard 副本集对象
- origen-sdk - 有没有办法将 if_enable 配置为始终有条件地通过或删除变量检查?
- xml - xml读取文件并写入xml文件
- javascript - 如何使用 click() 在 javascript 中单击一个元素,然后执行另一个函数?
- excel - 停止自动格式化单元格
- asp.net-core - 升级到预览版 6 后 Blazor 子应用程序出现 404 错误
- python - 集合文字和函数参数中的评估顺序保证
- python - 我在编写项目的这一部分时遇到问题
- c - 将数字中的数字 5 替换为 6