Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm packages not available when installed locally

I am working with npm on a web app and I found an issue when using some packages that requires terminal commands to run such like nodemon and concurrently

I installed it via

sudo npm install --save-dev nodemon

and when I try to use it via:

nodemon ./server.js

I get an error

nodemon command not found

and the same when I used concurrently

I tried also with

sudo npm install --save nodemon 

and it doesn't work.

it only work if I installed it globally

sudo npm install -g nodemon

Why I can't use it when install locally?

Note: I can found the executable file at node_modules/.bin

but this following not working as well

node_modules/.bin/nodemon ./server.js
like image 354
Peter Wilson Avatar asked Dec 13 '22 23:12

Peter Wilson


2 Answers

Global packages can be launched directly because they are saved in your PATH directory by default. If you saved a package locally you can see it on node_modules/.bin/ as you mentioned. So there are 2 ways to achieve what you want if you want to run an executable package if installed locally:

  • You can run it via terminal as ./node_modules/.bin/nodemon yourscript.js
  • Or via npm scripts in your package.json file, you do this:

    {
      "scripts": {
        "nodemon": "nodemon yourscript.js"
      }
    }  
    

    and execute npm run nodemon.

The 2nd approach works for both packages installed globally or locally.

I prefer installing packages locally, so my other apps won't get affected especially if I'm using different package versions per project.

UPDATE

On [email protected] onwards, it comes with a binary called npx. So you can run specific packages on the terminal just by npx [package] and it executes either your local or global npm package. In your case it should be something like npx nodemon server.js.

like image 68
JohnnyQ Avatar answered Dec 21 '22 09:12

JohnnyQ


Because it's in your node_modules/.bin folder, not your PATH.

You can either use ./node_modules/.bin/nodemon or $(npm bin)/nodemon to call nodemon.

like image 45
Tonni Avatar answered Dec 21 '22 10:12

Tonni