Search code examples
node.jslinuxopenwrt

Daemonize nodejs app on mediatek 7688


I'm using the Mediatek 7688 board running OpenWRT linux to create an IoT device. I have written the app in NodeJS and want it to be executed anytime the board boots up.

I have tried the solution given [here] (How to auto start an application in openwrt?) while this works but the board seems to be unable to complete the boot process (the NodeJS app doesn't exit). I have also tried the pm2 npm module but am running into issues with diskspace during installation.

Is there a way to reduce the "installed" size of the pm2 module? Or maybe a way to fire up the NodeJS scripts upon startup without using the module.

Thanks in advance!


Solution

  • So I was only using the pm2 module to ensure that:

    1. The program started at bootup
    2. The program was restarted in case it crashed

    To accomplish the first part and since my program was a node.js program, I made it into an executable file by adding #!/bin/sh env node as the first line in the file. Must ensure that the line ends in a LF line ending and not CRLF as in case of windows systems. Once done, I granted execute permission to the .js file by calling chmod a+x myfile.js.

    I then created an init script in the /etc/init.d folder and enabled that script - as explained here

    Now to ensure that the process restarted automatically in case it ever crashed, I a "cron script", like so and saved it a restart.sh in the root folder:

    #bin/sh
    if pgrep -f myfile.js > dev/null
    then
       #process is already running - do nothing
    else
       /etc/init.d/myprocess start
    fi
    

    And finally setup a crontab -e with * * * * * ~/restart.sh so that the restart.sh gets executed every minute to ensure that the process is running.