Not able to access globally installed node module

1.7k Views Asked by At

I tried to install @hapi/joi using command

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ sudo npm install @hapi/joi -g
+ @hapi/[email protected]
updated 1 package in 2.833s

I am able to see installed @hapi/joi in /usr/local/lib/node_modules

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js/tmp$ npm root -g
/usr/local/lib/node_modules

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js/tmp$ npm list -g @hapi/joi
/usr/local/lib
`-- @hapi/[email protected]  

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ tree /usr/local/lib/node_modules/@hapi/joi/ -L 1
/usr/local/lib/node_modules/@hapi/joi/
├── CHANGELOG.md
├── dist
├── lib
├── LICENSE.md
├── node_modules
├── package.json
└── README.md

3 directories, 4 files

But I am not able to access it

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ node
> var Joi = require('@hapi/joi'); // this is not working
{ Error: Cannot find module '@hapi/joi'
    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:22:18) code: 'MODULE_NOT_FOUND' }
> 
> 
> var Joi = require('/usr/local/lib/node_modules/@hapi/joi') // This is working
undefined

My node and npm are

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ which node
/usr/bin/node
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ node -v
v10.15.2
alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ npm -v
6.11.3

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ echo $NODE_PATH # this shows nothing

alok@alok-HP-Laptop-14s-cr1xxx:~/tmp/js$ node
> process['env']['PATH']
'/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
>

Why I am getting Error: Cannot find module '@hapi/joi'? How to troubleshoot this?

3

There are 3 best solutions below

0
On

you should have to use npm init it will make package.json then you can run you js file.

0
On

Have you checked your user folder? I have a node_module folder here /Users/<username>/node_modules It might be in there.

And you would have to change the $PATH maybe.

0
On

Adding /usr/local/lib/node_modules to NODE_PATH make it work

# Add this line in yuor ~/.bashrc
export NODE_PATH="/usr/local/lib/node_modules:$NODE_PATH"

or

# Add this line in yuor ~/.bashrc
export NODE_PATH="`npm root -g`:$NODE_PATH"

or

// Add this line at top in your node.js script
module.paths.push('/usr/local/lib/node_modules/')

Tested on Ubuntu 20.04, This should work in other Linux distributions also.