Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda