Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 580
Forivin Avatar asked Oct 22 '20 16:10

Forivin


2 Answers

No, once a process has exited it cannot perform any more operations, and there's no such thing as a "please foreground this after I exit"-type API for terminals that I've ever heard of.

The proper way to solve this is via a wrapper which monitors your process for failures and restarts. The wrapper then has control of stdio and passes those to its children.

You could achieve this via a simple bash loop, another node script, or you might just be able to leverage the NodeJS cluster module for this.

like image 71
Jonny Avatar answered Sep 30 '22 19:09

Jonny


As Jonny said, you'd need to have a process manager that handles the running of your application. Per the Node.js documentation for child_process, spawn() functions similar to popen() at the system level, which creates a forked process. This generally doesn't go into the foreground. Also, when a parent process exits, control is returned to either the calling process or the shell itself.

A popular process management solution is PM2, which can be installed via npm i -g pm2. (Not linking to their site/documentation here) PM2 is cross-platform, but it does require an "external" dependency that doesn't live within the codebase itself.

I would also be curious as to why you want a script that on exit restarts itself in the manner you're describing, since it seems like just re-running the script -- which is what PM2 and similar do -- would yield the same results, and not involve mucking around with process management manually.

like image 45
FibreChips Avatar answered Sep 30 '22 19:09

FibreChips