Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get process id from child process in node js

Tags:

node.js

i want to get process id from child process, for that i am using this command, this is what i tried, let unittest_api_backend_process_id = child_process_obj.pid; but it is not working, here i ave added my whole code, can anyone please check my below code and help me to resolve this issue ? any help will be really appreciated

const execSync = require('child_process').exec;
let child_process_obj = execSync('nodemon server.js ', {
    cwd: process.env.BACKEND_FOLDER_PATH
});
like image 832
taks Avatar asked Oct 15 '25 13:10

taks


1 Answers

I believe you need to use exec rather than execSync, this returns a child_process object that includes a PID.

execSync returns stdout, which won't give us the PID. Also, execSync won't return until the process exits which probably won't work in this case.

The callback passed to exec will be called with the output when process terminates.

I've updated to pass the cwd correctly.

const exec = require('child_process').exec;

let child_process_obj = exec('nodemon server.js ', {
    cwd: process.env.BACKEND_FOLDER_PATH
}, (error, stdout, stderr) => {
    // Callback will be called when process exits..
    if (error) {
        console.error(`An error occurred: `, error);
    } else {
        console.log(`stdout:`, stdout);
        console.log(`stderr:`, stderr);
    }
});

console.log(`Launched child process: PID: ${child_process_obj.pid}`);
like image 106
Terry Lennox Avatar answered Oct 18 '25 14:10

Terry Lennox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!