'Why is cron not executing my node.js script properly?

I am trying to run a node.js script from cron. It is supposed to read a .json-File, make an API call and then write the response to a .json-File.

When executing manually everything works fine.

This does it's job

sudo node ~/bots/gtaa/index.js

sudo crontab -e

29 9 * * 1-5 /usr/bin/node ~/bots/gtaa/index.js >> ~/gtaa-bot.log 2>&1

grep cron /var/log/syslog

May 11 09:29:01 raspberrypi CRON[54381]: (root) CMD (/usr/bin/node ~/bots/gtaa/index.js >> ~/gtaa-bot.log 2>&1)

My index.js uses the local .env-File

require('dotenv').config({ path: __dirname + '/.env' })

There also is no gtaa-bot.log-File in the home directory.

A very similar question has been asked here but there are no useful answers provided.



Solution 1:[1]

Well I have experienced this issue, more recently using Ubuntu 20.04.4 LTS

Ultimately what ends up happening is cron runs in a different environment and most likely is unable to find the correct path to node.

There are some ways to configure this, however I found a much easier solution ended up being to just have cron execute a bash script, that runs nvm and/or node.

For example, I have this setup to run every 20 minutes:

20 * * * * /bin/bash/ /home/user/nvm_cron.sh

And in my nvm_cron.sh file:

# Load nvm
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm use 16.14.0

# Run node program
cd /home/user/folder && node start.js

Dont forget to make sure the nvm_cron.sh file is executable

This way I have control over the version of node that I want to run for the script, and don't have to worry about messing with cron.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 treckstar