0

Hi I'm trying ping a port from nodejs. I use tcp-ping module. I want return available value from tcp.probe function. But i cant. Here is my code

var tcpp = require('tcp-ping');
function ping_port(callback){
tcpp.probe('10.5.177.52', 8080, function(err, available) {

    return_value = available;
    callback(available);
});
    }
function read() {
    console.log("Read done")
  return return_value;
 }
module.exports.ping = function()
{
    var port_status = ping_port(read);
    console.log(port_status);
    return port_status;

}

I resolved my problem by waiting for return_value varrible not equals undefined.Here is my code.

var tcpp = require('tcp-ping');
var return_value;

module.exports.ping = async function(page,ip)
{
   tcpp.probe(ip, 8080, function(err, available) {
    return_value = available;
}); 
 while(return_value === undefined)
 await page.waitFor(100);
 return return_value;
}

The page is a puppeteer modules function. I call await foo.ping('page' , 'ip') from my main async function and its done. I'm sorry about my bad English and coding. I'm beginner in coding.

Enes ÖZER
  • 11
  • 2

1 Answers1

1

You can't return a value from an async function. Instead, make the user of the module pass a callback to the ping function.

module.exports.ping = function(callback)
{
 ping_port(callback);
}

Use it like this:

function foo(port_status) {
    console.log("This is the port status: " + port_status);
}

const ping = require('./your_module');
ping(foo);
user835611
  • 2,309
  • 2
  • 21
  • 29
  • I try that code but i want use port_status value outside function foo and ping_port. I call ping(foo) in an async function. – Enes ÖZER Jul 18 '18 at 06:48