I have a nodejs application running on a live server. I start a new node process using the following command in Terminal of VSCODE by accessing the server through SSH.
nohup node filename.js &
Mostly I can see the process id using the following command in the VSCODE terminal.
netstat -lpn | grep 30001
This command gives the following output:
tcp6 0 0 :::30001 :::* LISTEN 21552/node
But, sometimes it doesnt show up any process id, as shown in the following output:
tcp6 0 0 :::30001 :::* LISTEN -
In case the process dies to due some technical error, it should get restarted automatically. I have executed the following code through a cron in every 5 minutes for this, which works.
const find = require('find-process');
var spawn = require('child_process').spawn;
find("port", "30001")
.then((list)=> {
console.log("list::", list);
if (!list.length) {
spawn('node', [`${__dirname}/filename.js`], {
detached: true,
stdio: 'ignore'
}).unref();
}
}, function (err) {
console.log(err.stack || err);
});
Following is my cron
*/5 * * * * node path-to-js-file/crontab.js
My Question:
- Why my node instance on port 30001 is sometimes not having a pid while the application contained inside it is still accessible?
kill -9
will need a Process Id which I dont have as showed above. How to kill such process through command so that it can be restarted?
CodePudding user response:
To show the proccess pid
you can use the process
module of nodejs.
var process = require('process');
console.log(`Process pid ${process.pid}`);
CodePudding user response:
You can get the parent process id by process.pid
. Similarly, when you create a child process using spawn or exec, it returns the child process object and this object contains the child parent id
const find = require('find-process');
var spawn = require('child_process').spawn;
find("port", "30001")
.then((list)=> {
console.log("list::", list);
if (!list.length) {
const childProcess = spawn('node', [`${__dirname}/filename.js`], {
detached: true,
stdio: 'ignore'
}).unref();
console.log(`Child Process ${childProcess.pid}`);
}
}, function (err) {
console.log(err.stack || err);
});