Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to include a command-line in a Node module without global install?

I have a small Node module that includes a command line script in the bin directory.

    "bin": {
        "generate": "./bin/generate.js"
    }

The generate.js script is properly executable.

This all works fine if I run npm install -g. But I'd prefer not to globally install and only have the command generate work from inside the module folder. If I run npm install from the module folder, it does correctly install all of the dependencies in a node_modules subdirectory. But then generate from the command like gives me "No such file or directory."

Thx.

like image 465
Chris Wilson Avatar asked Nov 24 '13 21:11

Chris Wilson


People also ask

Should node install globally?

A package should be installed globally when it provides an executable command that you run from the shell (CLI), and it's reused across projects. You can also install executable commands locally and run them using npx, but some packages are just better installed globally.

What is the command used for installing the modules in Nodejs?

To install the required modules for this project, type: npm i.

Does npm install packages globally?

How does npm install packages globally? Global modules are installed in the /usr/local/lib/node_modules project directory in the standard system, which is the system's root. Print the location of all global modules on your system using this command.


1 Answers

I never install node modules using -g. My solution for your problem is to add this to my $PATH

# add this to ~/.bashrc, ~/.zshrc, or ~/.profile, etc
export PATH="./node_modules/.bin:$PATH"

Now, so long as your in the root of your module, you can access any binaries that have been installed as modules.


As an example, less is commonly installed with

npm install -g less

However, if you have your PATH modified as described above, you could something like this

cd my_node_module
npm install --save less
lessc less/style.less css/style.css

Without the PATH modification, you would've seen

command not found: lessc

If you don't feel like altering your PATH, you can access the binary directly

cd my_node_module
npm install --save lessc
./node_modules/.bin/lessc a.less a.css

Yay, no more npm install -g ...

like image 99
maček Avatar answered Sep 22 '22 14:09

maček