jvb1nw
Last Updated: February 25, 2016
·
311
· samueljmurray

Executing local node packages

When you install node packages, you often need to execute them. That's fine if you install them globally and you've got the global package directory on your PATH:

$ npm install -g karma

Now you can run

$ karma init my.conf.js

But if you only want to install a package locally, it won't be accessible on your PATH.

Quite a few packages get around this by providing a -cli package; karma-cli for example. This is slightly annoying though, installing a package, then having to install it's -cli package. That's if it even has a -cli package.

However, there is a handy (if slightly hacky) work-around that I found in this article.

Write a small shell script. This is mine:

#!/bin/bash
bin=$1
shift
./node_modules/.bin/$bin $@

It takes the command you want to execute with its parameters and runs it from the node_modules/.bin directory in the project directory you're working from.

Save it as "npm_exec" and make executable:

$ chmod +x npm_exec

Move it to /usr/local/bin or another directory that is on your PATH:

$ mv npm_exec /usr/local/bin

Now you can run locally installed node packages from your project directory like this:

$ npm_exec karma init my.conf.js