2

I have a javascript program, which runs on nodejs. If I run the following command:

node app.js

It keeps running but sometimes it exits. But I want to start it again automatically when it exits.

Is there any command to do so for Linux systems? Note that I don't want to use cron jobs.

1 Answer 1

8

Quick and dirty way : If using bash then what about a simple bash script like :

#!/usr/bin/bash
while true
do
  node app.js
done

BTW, this is wrongdoing since you don't take into account the reasons why your task exited and there might be very good reasons for not restarting it. Not to say that it could also crash at startup, be oomkilled…


More canonical way under a systemd-ized linux : (suggested as part of @Kusalananda note and inspired by The ultimate guide to deploying your node app on Linux) :

Assuming that app.js starts with the #!/usr/bin/env node declaration and the file app.js is marked executable,

Design a new service : Create a .service file in the /etc/systemd/system directory if needed system-wide or ~/.config/systemd/user directory if only needed by your user, as follows :

[Unit]
Description=        #(Whatever String You Want)
After=              #(Any service that should be started before, ex. network.target)
[Service]
ExecStart=          #(Key in the absolute path of app.js)
Restart=always      #(This will ensure the automatic restart)
User=               #(TBD depending on your system & wishes)
Group=              #(TBD depending on your system & wishes)
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=   # (Absolute path of app.js working dir.)
[Install]
WantedBy=           # multi-user.target or default.target according to your needs

You should now be able to start it : systemctl --user start service_filename

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .