Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use executables from a package installed locally in node_modules?

How do I use a local version of a module in node.js. For example, in my app, I installed coffee-script:

npm install coffee-script 

This installs it in ./node_modules and the coffee command is in ./node_modules/.bin/coffee. Is there a way to run this command when I'm in my project's main folder? I guess I'm looking for something similar to bundle exec in bundler. Basically, I'd like to specify a version of coffee-script that everyone involved with the project should use.

I know I can add the -g flag to install it globally so coffee works fine anywhere, but what if I wanted to have different versions of coffee per project?

like image 805
typeoneerror Avatar asked Mar 13 '12 07:03

typeoneerror


People also ask

How do I run a node module?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.


1 Answers

UPDATE: As Seyeong Jeong points out in their answer below, since npm 5.2.0 you can use npx [command], which is more convenient.

OLD ANSWER for versions before 5.2.0:

The problem with putting

./node_modules/.bin 

into your PATH is that it only works when your current working directory is the root of your project directory structure (i.e. the location of node_modules)

Independent of what your working directory is, you can get the path of locally installed binaries with

npm bin 

To execute a locally installed coffee binary independent of where you are in the project directory hierarchy you can use this bash construct

PATH=$(npm bin):$PATH coffee 

I aliased this to npm-exec

alias npm-exec='PATH=$(npm bin):$PATH' 

So, now I can

npm-exec coffee 

to run the correct copy of coffee no matter of where I am

$ pwd /Users/regular/project1  $ npm-exec which coffee /Users/regular/project1/node_modules/.bin/coffee  $ cd lib/ $ npm-exec which coffee /Users/regular/project1/node_modules/.bin/coffee  $ cd ~/project2 $ npm-exec which coffee /Users/regular/project2/node_modules/.bin/coffee 
like image 128
regular Avatar answered Sep 23 '22 21:09

regular