Directly call globally installed Node.js modules

2019-02-18 00:16发布

问题:

Supposed I want to write a module for Node.js that shall be installed globally. I do not want to write any C++ (or something else), but plain Node.js code.

Basically, this is very easy. Just write the module, and install it using npm install -g.

Now, most globally installed modules provide the possibility to call them directly, e.g. you can type express at your command prompt and run the globally installed application bootstrapper of Express.

Now my question is: How do I achieve this?

If I simply install a module globally, this does not make one of the files available as an executable, or puts that file onto the PATH.

What steps do I need to do in order to achieve this?

So my question is basically: What steps need to be done to create globally available executable out of a "normal" Node.js module?

回答1:

You need to write an executable file. This is what will be executed when a user types your command. Here's an example taken from JSHint:

#!/usr/bin/env node

require("./../src/cli/cli.js").interpret(process.argv);

Convention says to place this file in a bin directory in the root of your project. You then just need to update your package.json file to tell it where to find your executable:

{
    "bin": {
        "jshint": "./bin/jshint"
    }
}

In this case, the executable file can be run from the terminal with the jshint command. When it runs, it simply requires another file and calls a method in it, passing through any command line arguments.