Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
Why this is showing type error in NodeJS while using ping module?

I'm trying to make a basic app to ping an IP. So my HTML form takes one input IP and post it to NodeJS. I'm using ping module to get the results. it works fine if I enter an IP statically but when I try to get IP by HTML form it just breaks. This is how my code looks.

app.post("/",function(req,res){
   console.log(req.body);
   var ip= req.body.ip;
   console.log(typeof(ip));
   var msg;
   var hosts = [ip];
   hosts.forEach(function(host){
       ping.sys.probe(host, function(isAlive){
           console.log(isAlive);
           msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
           console.log(msg);
      });
  });
res.write(msg);
res.send();
}); 

This is what comes on console

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The way I see it, this is what is happening:

  1. You issue a ping request. Note, that it takes a callback function as a parameter. This suggests that this is an asynchronous I/O operation.
  2. You execute
res.write(msg);
res.send();

At the time msg is still undefined and therefore I'm guessing that res.write(msg) is in fact the line 30 of app.js file that the error is all about

  1. Only then the callback function is executed, but it's too late

I would recommend changing it as follows

app.post("/",function(req,res){
   console.log(req.body);
   const ip= req.body.ip;
   console.log(typeof(ip));
   ping.sys.probe(ip, function(isAlive){
      console.log(isAlive);
      const msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
      console.log(msg);
      res.write(msg);
      res.send();
   });
}); 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda