Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!