'Can't import global package in Node even though NODE_PATH is set?

I'm trying to import a globally installed pkg located at /some/path. I have set NODE_PATH in ~/.bash_profile. I am able to do 'echo $NODE_PATH' and see my path in a terminal. However node 11.10.1 still isn't finding the pkg. From what I read here https://nodejs.org/docs/v0.4.2/api/modules.html#all_Together require.paths should be initialized from this env var. However if I log require.paths, it is not set, console.log(require.paths) is undefined. How can I fix this?

console.log(process.env.NODE_PATH)

var i = require('promised-io')

exact error msg: Uncaught Error: Cannot find module 'promised-io'



Solution 1:[1]

Have had the same problem with node v16.14.0 as installed in Ubuntu 21.10. The environment variable $NODE_PATH seems to be ignored, and the global install path as used by npm (/usr/local/lib/node_modules) is not searched by node. For me I found two workarounds:

  • Add module.paths.push('/usr/local/lib/node_modules'); to the *.js

or if you don't want to patch other peoples tools but still want to provide global installed packets e.g. for multiple users of a build server, you can simply fix this with a symbolic link. Looking into Node.js v16.14.0 documentation - Loading from the global folders shows, that node still searches in $PREFIX/lib/node but no longer in $PREFIX/lib/node_modules. So we can solve this deviation between npm and node global default path by

  • sudo ln -sf /usr/local/lib/node_modules /usr/local/lib/node

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