This is not a duplicate.
Answers in the below do not work or are irrelevant:
NodeJS require a global module/package
This link to the official documentation also does not solve the problem.
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
Problem:
I use node.js not only for actual backend projects and frontend packing, but I also have various utilities scaattered around my file system to do some trivial (and sometimes not so trivial) stuff, like updating prompt, showing help, checking runnning processes, system status, listing particular files, automating my daily routine tasks, etc. Fo such scripts I need to require some globally available js files that I want to keep somewhere in a file system. Right now my only option is to use require(process.HOME + '/js/somefile')
syntax.
I tried putting scripts in:
$HOME/node_modules
$HOME/node_libraries
$HOME/.node_modules
$HOME/.node_libraries
Also tried to export NODE_PATH
variable.
Why not npm publish
? I have literally hundreds of node.js based CLI utilities. And dozens of shared JavaScript. Publishing and reinstalling globally works but is cumbersome, I tried.
So what is a solution?
What I need is simply have a lib.js
in $HOME/js/lib.js
which I could require from everywhere on my system by just typing require('lib')
. Note that the caller program can also be anywhere on the filesystem.
UPDATE
the small script:
console.log(process.env[ 'NODE_PATH' ])
require('lib')
Will print:
/home/me/js:/home/me/soft/node/node-v6.1.0-linux-x64/lib/node_modules/
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'lib'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/home/me/test.js:2:1)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
Of course the file is in ~/js
:
$ pwd
/home/me
$ cat ~/js/lib.js
console.log('it loaded')
$ node -v
v10.7.0
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.1 LTS
Release: 18.04
Codename: bionic