Sunday, 25 October 2020

How to restart a Node.js application and handover the new process to the console

The following Node.js script can restart itself and will even still print to the correct console (or terminal if you prefer), but it will no longer be running in the foreground, as in you can't exit it with Ctrl+C anymore (see screenshot) etc:

console.log("This is pid " + process.pid);
setTimeout(function () {
    process.on("exit", function () {
        require("child_process").spawn(process.argv.shift(), process.argv, {
            cwd: process.cwd(),
            detached : true,
            stdio: "inherit"
        });
    });
    process.exit();
}, 5000);

I've already tried detached: true vs detached: false, but obviously this didn't solve the problem...

Is there a way to make the new node process run in the foreground, replacing the old one? Or this this not possible?

I know that in Bash you can pull a program back from the background like this:

  $ watch echo "runs in background" &
  $ fg # pulls the background process to the foreground

But I'm not looking for a Bash command or so, I'm looking for a programmatic solution within the Node.js script that works on any platform.

enter image description here



from How to restart a Node.js application and handover the new process to the console

No comments:

Post a Comment