Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get cron job running Node.js script to read variables from .env file?

I've currently got a cron job setup where it runs a Node.js script. The Node.js script uses the dotenv package to read a .env file that has some API keys.

When I run the Node.js script from the command line, the variables are read correctly from the .env file and works with my Node.js script.

But when cron runs the Node.js script, the variables that I'm trying to set return undefined.

00 05 * * * /home/michaellee/.nvm/versions/node/v6.10.0/bin/node /home/michaellee/index.js >> /home/michaellee/output.log

The .env file resides in the same level as the index.js file.

The cron job is set using crontab -e from the user michaellee, the same user that has the files on Ubuntu.

like image 401
michaellee Avatar asked May 24 '17 18:05

michaellee


2 Answers

I just change the path on dotenv config and it worked for me

const dotenv = require('dotenv');    
dotenv.config({ path: __dirname + '/../.env' });
like image 84
Alan Bacelar Avatar answered Sep 23 '22 17:09

Alan Bacelar


I think it'd be less of a headache to take the contents out of the .env file and load them into a JSON file. Then, you can just require the JSON file and load in the data. Much each & doesn't require any plugins, & it would work w/ Cron seamlessly.

like image 37
Colby Cox Avatar answered Sep 22 '22 17:09

Colby Cox