How can I restart a Node.js app from within itself (programmatically)?
Asked Answered
F

8

29

How can I create an app that can restart itself? I want to create an app that sets up a web-admin which can restart itself. Is this possible? If so, how? I was thinking this might be possible with the process global variable that is built into node.

Fatso answered 20/2, 2012 at 7:49 Comment(1)
Several modules from github.com/joyent/node/wiki/modules#wiki-build-and-deployment claim to make that easy.Malva
S
38

It is possible without external dependencies:

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);

source : https://gist.github.com/silverwind/d0802f7a919ae86ff25e

Sparhawk answered 19/10, 2017 at 8:37 Comment(2)
Yes, it works well on my local, but it doens't work on docker container. It would be great if you provide me some advice.Platelet
It wors, but . . . how to stop it? In other words, if I want to stop the process as I need to change something in the script, how can I do it? It looks like when restarts, ignore the changes done in the existing scripts!Pastime
B
14

I know it's a little late to reply however I had a similar requirement. I wanted to restart my node process whenever I made a configuration change. I'm using pm2 to manage my node processes so it turned out to be really easy.

After making a configuration change, i execute process.exit() from within the node process. As far as I can see, the process exits then pm2 restarts the process fine.

Not sure yet if there are any side effects but it seems to be working fine for me right now.

Bess answered 22/7, 2016 at 16:24 Comment(0)
P
5
  1. you can run your app using child process and manipulate it how needed: https://nodejs.org/api/child_process.html

  2. use forever, pm2 or whatever thing to restart after death and kill itself with process.exit() https://nodejs.org/api/process.html

Pronator answered 29/4, 2017 at 21:54 Comment(0)
D
0

Not from the process itself but it might be useful to people that land on here.

I add it to systemd of Linux and it starts up on network.target logs the console to /var/logs/<app>.log and it restarts on failure. So you can just force a process.exit on it.

sudo touch /lib/systemd/system/<app>.service
sudo tee -a /lib/systemd/system/<app>.service > /dev/null <<EOT
[Unit]
Description=<app>
After=network.target
[Service]
Type=simple
User=$USER
ExecStart=/bin/node --prefix /home/$USER/path/to/app
Restart=on-failure # or always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=<app>
[Install]
WantedBy=multi-user.target
EOT

sudo touch /etc/rsyslog.d/<app>.conf
sudo tee -a /etc/rsyslog.d/<app>.conf > /dev/null <<EOT
if $programname == '<app>' then /var/log/<app>.log
& stop
EOT

sudo systemctl enable <app>
sudo systemctl daemon-reload
sudo systemctl restart rsyslog
sudo systemctl start <app>
Dualpurpose answered 28/7, 2021 at 14:49 Comment(0)
A
0

i know the question is a little old but it may help someone later : i would suggest to use nodeJS Cluster & Worker for this purpose!

const cluster = require('cluster');

if (cluster.isMaster ?? cluster.isPrimary) {
    cluster.fork();
    cluster.on("exit", (worker, code) => {
        console.log(`[master] worker #${worker.id} down, restarting\n`);
        cluster.fork();
    });
    process.on("SIGINT", () => { });
} else {
    console.log(`\nnew worker #${cluster.worker.id}\n`);
    process.on("SIGINT", () => {
        console.log(`[worker#${cluster.worker.id}] SIGINT received! dying gracefully!!\n`);
        process.exit(0);
    });
}

try running it with nodejs and hitting the ctrl+c combination.

it will just restart with the new code running.
you can kill the master with sending any signal other than SIGINT

Abracadabra answered 22/10, 2022 at 12:2 Comment(0)
C
0

for temporary purposes, you might run with nodemon and use this hecky function:

restartWithFile () {
    fs.writeFileSync(__dirname + '/restart.js', '1');
}

so, nodemone will react on filechange and will restart.

Chiastic answered 22/12, 2023 at 17:36 Comment(0)
B
-2

create file nodemon.sh

#!/usr/bin/env bash
while true; do
            sleep 20
            echo "// nodemon $(date)" >config.js
        done

permition sudo chmod +x nodemon.sh

run it

./nodemon.sh

Bufford answered 7/3, 2022 at 13:2 Comment(0)
U
-3

Yes, upstart will restart your process without a nodemon.

npm install -g nodemon
sudo nodemon server.js

nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

Unmannered answered 29/9, 2017 at 12:59 Comment(1)
I don't think the OP wants their service to keep restarting forever. Rather, they seem to want to trigger a restart under specific conditions, or exit if those conditions are not met.Abney

© 2022 - 2024 — McMap. All rights reserved.