直接调用全局安装的Node.js模块 [英] Directly call globally installed Node.js modules

查看:344
本文介绍了直接调用全局安装的Node.js模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想为Node.js编写一个模块,该模块将在全球范围内安装.我不想编写任何C ++(或其他东西),而不想编写简单的Node.js代码.

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.

基本上,这很容易.只需编写模块,然后使用npm install -g进行安装.

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

现在,大多数全局安装的模块都可以直接调用它们,例如您可以在命令提示符下键入express并运行Express全局安装的应用程序引导程序.

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?

如果仅在全局安装模块,则不会使其中一个文件作为可执行文件可用,也不会将该文件放到PATH上.

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?

所以我的问题基本上是:要从正常" Node.js模块中创建全局可用的可执行文件,需要执行哪些步骤?

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

推荐答案

您需要编写一个可执行文件.这是用户键入命令时将执行的操作.这是取自 JSHint 的示例:

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表示将此文件放置在项目根目录的 bin 目录中.然后,您只需要更新您的 package.json 文件,告诉它在哪里可以找到您的可执行文件:

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"
    }
}

在这种情况下,可执行文件可以使用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.

这篇关于直接调用全局安装的Node.js模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆