First:
In windows, if you use:
ping google.com
You will get only 4 information ping, but on Ubuntu, if you use that command, the ping can't stop until you stop it with Ctrl+C
.
To fix this we need to use -c flag. The -c option tells ping program to stop after sending (or receiving) specified number of ECHO_RESPONSE packets.
Second:
you need to use res.send
to send back the ping response but due to your callback
function i.e puts you don't have the access for res
and req
.
Use this wrapper func to pass another arguments you want to access with your callback
function execute(command, callback, res) {
exec(command, function(error, stdout, stderr) {
// Notice extra params I have passed here^, ^
callback(error, stdout, stderr, res);
});
}
and you can use this as
execute("ping -c 2 google.com", puts, /*pass extra params*/ res);
and catch extra params here after your callback
function
||
---------- \/
function execute(command, callback, res) {
...
}
Complete code:
var exec = require('child_process').exec;
function puts(error, stdout, stderr, res) {
// Notice extra params here ^
if (error) {
console.log("error", "Error connecting");
result = "Failed";
console.log(result)
} else {
sys.puts(stdout)
result = "Success"
console.log(result)
//send response to client
res.send(result)
}
}
//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res) {
execute("ping -c 1 google.com", puts, /*pass extra params*/ res);
});
function execute(command, callback, res) {
exec(command, function(error, stdout, stderr) {
// Notice extra params I have passed here^, ^
callback(error, stdout, stderr, res);
});
}
Ref:
https://askubuntu.com/questions/200989/ping-for-4-times
Get the output of a shell command in node.js