Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't import modules into a node script if it runs from cron

I have the module underscore installed globally with npm. if I run the script

/usr/local/bin/node /home/olmo/project/processDrivesMultiUser.js

it will run ok wherever I am on the path, but if I run a cronjob like this:

3,18,33,48, * * * * /usr/local/bin/node /home/olmo/project/processDrivesMultiUser.js

I get this error:

Date: Wed, 10 Sep 2014 16:26:01 -0600
From: Cron Daemon <[email protected]>
To: [email protected]
Subject: Cron <olmo@db> /usr/local/bin/node /home/olmo/project/processDrivesMultiUser.js


module.js:340
    throw err;
          ^
Error: Cannot find module 'underscore'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/olmo/sandbox/api_ievwebapp/parseAdminScripts/processDrivesMultiUser.js:20:9)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

somehow it can't find the module underscore if it runs via cron. I made the cron entry for the same username I'm using to run the script manually.

any ideas?

like image 916
otmezger Avatar asked Sep 10 '14 22:09

otmezger


People also ask

Is node-cron blocking?

First, node-cron has the same merits and demerits as Node. js, being a runtime of JavaScript, which happens to be a non-blocking single-threaded language that uses the event loop.

How do I resolve Cannot find module error using node js?

To solve the "Cannot find module" error in Node. js, make sure to install the package from the error message if it's a third-party package, e.g. npm i somePackage . If you get the error with a local module, make sure to point the node command to a file that exists.

Can not find module node js?

To fix the Cannot find module error, simply install the missing modules using npm . This will install the project's dependencies into your project so that you can use them. Sometimes, this might still not resolve it for you. In this case, you'll want to just delete your node_modules folder and lock file ( package-lock.


1 Answers

I could find the answer based on the comment by mu is too short.

I modified the crontab to include the environmental variable NODE_PATH

3,18,33,48, * * * * export NODE_PATH=/usr/local/lib/node_modules/ && /usr/local/bin/node /home/olmo/project/processDrivesMultiUser.js

now I'm able to use modules in node.js if called by cron.

like image 87
otmezger Avatar answered Sep 28 '22 04:09

otmezger