首页 > 解决方案 > 杀死子进程执行

问题描述

我需要你的帮助。我想通过 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 ...... 没有终止。

我期待您的支持,并希望有人能告诉我我做错了什么。

最好的问候汉斯

标签: javascripthtmlnode.js

解决方案


由于无法看到您的代码,很难预测为什么它在您的情况下不起作用。但是您可以尝试下一个效果很好的方法。当然它很脏,只是一个例子。

下一个代码用于“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 });
  })
});


推荐阅读