如何通过npm和package.json使用Node.js模块

news/2024/7/5 9:26:49

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

Because of such features as its speedy Input/Output (I/O) performance and its well-known JavaScript syntax, Node.js has quickly become a popular runtime environment for back-end web development. But as interest grows, larger applications are built, and managing the complexity of the codebase and its dependencies becomes more difficult. Node.js organizes this complexity using modules, which are any single JavaScript files containing functions or objects that can be used by other programs or modules. A collection of one or more modules is commonly referred to as a package, and these packages are themselves organized by package managers.

由于其快速的输入/输出(I / O)性能和众所周知JavaScript语法等功能, Node.jsSwift成为后端Web开发的流行运行时环境。 但是随着兴趣的增长,将构建更大的应用程序,并且管理代码库及其依赖关系的复杂性变得更加困难。 Node.js使用模块来组织这种复杂性, 模块是包含可被其他程序或模块使用的函数或对象的任何单个JavaScript文件。 一个或多个模块的集合通常称为程序包 ,这些程序包本身由程序包管理器组织。

The Node.js Package Manager (npm) is the default and most popular package manager in the Node.js ecosystem, and is primarily used to install and manage external modules in a Node.js project. It is also commonly used to install a wide range of CLI tools and run project scripts. npm tracks the modules installed in a project with the package.json file, which resides in a project’s directory and contains:

Node.js程序包管理器(npm)是Node.js生态系统中默认的,最受欢迎的程序包管理器,主要用于安装和管理Node.js项目中的外部模块。 它还通常用于安装各种CLI工具和运行项目脚本。 npm使用package.json文件跟踪项目中安装的模块,该文件位于项目目录中,并且包含:

  • All the modules needed for a project and their installed versions

    项目所需的所有模块及其安装版本
  • All the metadata for a project, such as the author, the license, etc.

    项目的所有元数据,例如作者,许可证等。
  • Scripts that can be run to automate tasks within the project

    可以运行脚本来自动执行项目中的任务

As you create more complex Node.js projects, managing your metadata and dependencies with the package.json file will provide you with more predictable builds, since all external dependencies are kept the same. The file will keep track of this information automatically; while you may change the file directly to update your project’s metadata, you will seldom need to interact with it directly to manage modules.

当您创建更复杂的Node.js项目时,使用package.json文件管理元数据和依赖项将为您提供更可预测的构建,因为所有外部依赖项均保持不变。 该文件将自动跟踪此信息; 尽管您可以直接更改文件以更新项目的元数据,但几乎不需要直接与文件进行交互来管理模块。

In this tutorial, you will manage packages with npm. The first step will be to create and understand the package.json file. You will then use it to keep track of all the modules you install in your project. Finally, you will list your package dependencies, update your packages, uninstall your packages, and perform an audit to find security flaws in your packages.

在本教程中,您将使用npm管理软件包。 第一步将是创建和理解package.json文件。 然后,您将使用它来跟踪项目中安装的所有模块。 最后,您将列出您的程序包依赖性,更新程序包,卸载程序包并执行审核以发现程序包中的安全漏洞。

先决条件 (Prerequisites)

To complete this tutorial, you will need:

要完成本教程,您将需要:

  • Node.js installed on your development machine. This tutorial uses version 10.17.0. To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04. By having Node.js installed you will also have npm installed; this tutorial uses version 6.11.3.

    在您的开发机器上安装了Node.js。 本教程使用版本10.17.0。 要将其安装在macOS或Ubuntu 18.04上,请遵循如何在macOS上安装Node.js并创建本地开发环境中的步骤,或如何在Ubuntu 18.04上安装Node.js的 使用PPA安装部分中的步骤 。 通过安装Node.js,您还将安装npm。 本教程使用版本6.11.3。

第1步-创建package.json文件 (Step 1 — Creating a package.json File)

We begin this tutorial by setting up the example project—a fictional Node.js locator module that gets the user’s IP address and returns the country of origin. You will not be coding the module in this tutorial. However, the packages you manage would be relevant if you were developing it.

我们通过设置示例项目开始本教程,该项目是一个虚构的Node.js locator模块,该模块获取用户的IP地址并返回原籍国。 您将不在本教程中编码模块。 但是,如果您正在开发软件包,则您管理的软件包将是相关的。

First, you will create a package.json file to store useful metadata about the project and help you manage the project’s dependent Node.js modules. As the suffix suggests, this is a JSON (JavaScript Object Notation) file. JSON is a standard format used for sharing, based on JavaScript objects and consisting of data stored as key-value pairs. If you would like to learn more about JSON, read our Introduction to JSON article.

首先,您将创建一个package.json文件,以存储有关项目的有用元数据,并帮助您管理项目的依赖Node.js模块。 如后缀所示,这是一个JSON(JavaScript对象表示法)文件。 JSON是一种用于共享的标准格式,基于JavaScript对象 ,由存储为键值对的数据组成。 如果您想了解有关JSON的更多信息,请阅读我们的JSON简介文章。

Since a package.json file contains numerous properties, it can be cumbersome to create manually, without copy and pasting a template from somewhere else. To make things easier, npm provides the init command. This is an interactive command that asks you a series of questions and creates a package.json file based on your answers.

由于package.json文件包含许多属性,因此手动创建可能很麻烦,而无需从其他地方复制和粘贴模板。 为了使事情变得容易,npm提供了init命令。 这是一个交互式命令,它会询问您一系列问题,并根据您的答案创建一个package.json文件。

使用init命令 (Using the init Command)

First, set up a project so you can practice managing modules. In your shell, create a new folder called locator:

首先,设置一个项目,以便您可以练习管理模块。 在您的外壳中,创建一个名为locator的新文件夹:

  • mkdir locator

    mkdir 定位器

Then move into the new folder:

然后移至新文件夹:

  • cd locator

    cd 定位器

Now, initialize the interactive prompt by entering:

现在,通过输入以下内容来初始化交互式提示:

  • npm init

    npm初始化

Note: If your code will use Git for version control, create the Git repository first and then run npm init. The command automatically understands that it is in a Git-enabled folder. If a Git remote is set, it automatically fills out the repository, bugs, and homepage fields for your package.json file. If you initialized the repo after creating the package.json file, you will have to add this information in yourself. For more on Git version control, see our Introduction to Git: Installation, Usage, and Branches series.

注意 :如果您的代码将使用Git进行版本控制,请首先创建Git存储库,然后运行npm init 。 该命令会自动了解它在启用了Git的文件夹中。 如果设置了Git远程控制器,它将自动为package.json文件填写repositorybugshomepage字段。 如果在创建package.json文件之后初始化了package.json ,则必须在自己中添加此信息。 有关Git版本控制的更多信息,请参见我们的Git简介:安装,使用和分支 。

You will receive the following output:

您将收到以下输出:


   
Output
This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (locator)

You will first be prompted for the name of your new project. By default, the command assumes it’s the name of the folder you’re in. Default values for each property are shown in parentheses (). Since the default value for name will work for this tutorial, press ENTER to accept it.

首先将提示您输入新项目的name 。 默认情况下,该命令假定它是您所在的文件夹的名称。每个属性的默认值都显示在括号() 。 由于name的默认值适用于本教程,因此请按ENTER接受。

The next value to enter is version. Along with the name, this field is required if your project will be shared with others in the npm package repository.

输入的下一个值是version 。 如果要与npm软件包存储库中的其他项目共享您的项目,则该字段与name一起是必填字段。

Note: Node.js packages are expected to follow the Semantic Versioning (semver) guide. Therefore, the first number will be the MAJOR version number that only changes when the API changes. The second number will be the MINOR version that changes when features are added. The last number will be the PATCH version that changes when bugs are fixed.

注意: Node.js软件包应遵循语义版本控制 (Semver)指南。 因此,第一个数字将是MAJOR版本号,仅当API更改时才会更改。 第二个数字是MINOR版本,在添加功能时会更改。 最后一个数字将是修正错误后更改的PATCH版本。

Press ENTER so the default version is accepted.

ENTER ,以接受默认版本。

The next field is description—a useful string to explain what your Node.js module does. Our fictional locator project would get the user’s IP address and return the country of origin. A fitting description would be Finds the country of origin of the incoming request, so type in something like this and press ENTER. The description is very useful when people are searching for your module.

下一个字段是description一个有用的字符串,用于解释Node.js模块的功能。 我们的虚构locator项目将获取用户的IP地址并返回原籍国。 合适的description为“ Finds the country of origin of the incoming request ,因此键入类似内容,然后按ENTER 。 当人们搜索您的模块时,该description非常有用。

The following prompt will ask you for the entry point. If someone installs and requires your module, what you set in the entry point will be the first part of your program that is loaded. The value needs to be the relative location of a JavaScript file, and will be added to the main property of the package.json. Press ENTER to keep the default value.

以下提示将要求您提供entry point 。 如果有人安装并requires您的模块,则在entry point设置的内容将是程序的第一部分。 该值必须是JavaScript文件的相对位置,并将被添加到package.jsonmain属性中。 按ENTER保留默认值。

Note: Most modules have an index.js file as the main point of entry. This is the default value for a package.json’s main property, which is the point of entry for npm modules. If there is no package.json, Node.js will try to load index.js by default.

注意 :大多数模块都有一个index.js文件作为主要入口。 这是package.jsonmain属性的默认值,这是npm模块的入口点。 如果没有package.json ,Node.js将默认尝试加载index.js

Next, you’ll be asked for a test command, an executable script or command to run your project tests. In many popular Node.js modules, tests are written and executed with Mocha, Jest, Jasmine, or other test frameworks. Since testing is beyond the scope of this article, leave this option empty for now, and press ENTER to move on.

接下来,将要求您提供test command ,可执行脚本或命令来运行项目测试。 在许多流行的Node.js模块中,测试都是使用Mocha , Jest , Jasmine或其他测试框架编写和执行的。 由于测试不在本文讨论范围之内,因此请暂时将此选项留空,然后按ENTER继续。

The init command will then ask for the project’s GitHub Repository. You won’t use this in this example, so leave it empty as well.

然后, init命令将要求提供项目的GitHub Repository 。 在本示例中,您将不使用此功能,因此也请保留为空。

After the repository prompt, the command asks for keywords. This property is an array of strings with useful terms that people can use to find your repository. It’s best to have a small set of words that are really relevant to your project, so that searching can be more targeted. List these keywords as a string with commas separating each value. For this sample project, type ip,geo,country at the prompt. The finished package.json will have three items in the array for keywords.

在存储库提示后,该命令将询问keywords 。 此属性是带有有用术语的字符串数组,人们可以使用这些术语来查找您的存储库。 最好使用与您的项目真正相关的一小部分单词,这样搜索可以更有针对性。 将这些关键字作为字符串列出,并用逗号分隔每个值。 对于此示例项目,在提示符下键入ip,geo,country 。 完成的package.json将在数组中包含三个keywords

The next field in the prompt is author. This is useful for users of your module who want to get in contact with you. For example, if someone discovers an exploit in your module, they can use this to report the problem so that you can fix it. The author field is a string in the following format: "Name \<Email\> (Website)". For example, "Sammy \<sammy@your_domain\> (https://your_domain)" is a valid author. The email and website data are optional—a valid author could just be a name. Add your contact details as an author and confirm with ENTER.

提示中的下一个字段是author 。 这对于想要与您联系的模块用户很有用。 例如,如果某人在您的模块中发现了漏洞,则可以使用此漏洞报告问题,以便您进行修复。 author字段是采用以下格式的字符串: " Name \< Email \> ( Website )" 。 例如, "Sammy \<sammy@your_domain\> (https://your_domain)"是有效的作者。 电子邮件和网站数据是可选的-有效的作者可能只是名字。 添加您的联系方式作为作者,然后按ENTER

Finally, you’ll be prompted for the license. This determines the legal permissions and limitations users will have while using your module. Many Node.js modules are open source, so npm sets the default to ISC.

最后,系统会提示您输入license 。 这确定了用户在使用您的模块时将具有的法律许可和限制。 许多Node.js模块都是开源的,因此npm将默认值设置为ISC 。

At this point, you would review your licensing options and decide what’s best for your project. For more information on different types of open source licenses, see this license list from the Open Source Initiative. If you do not want to provide a license for a private repository, you can type UNLICENSED at the prompt. For this sample, use the default ISC license, and press ENTER to finish this process.

此时,您将检查许可选项,并确定最适合您的项目的项目。 有关不同类型的开源许可证的更多信息,请参阅《开源计划》中的此许可证列表 。 如果您不想为私有存储库提供许可证,则可以在提示符下键入UNLICENSED 。 对于此示例,使用默认的ISC许可证,然后按ENTER以完成此过程。

The init command will now display the package.json file it’s going to create. It will look similar to this:

现在, init命令将显示将要创建的package.json文件。 它看起来类似于:


   
Output
About to write to /home/sammy/locator/package.json: { "name": "locator", "version": "1.0.0", "description": "Finds the country of origin of the incoming request", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "ip", "geo", "country" ], "author": "Sammy <sammy@your_domain> (https://your_domain)", "license": "ISC" } Is this OK? (yes)

Once the information matches what you see here, press ENTER to complete this process and create the package.json file. With this file, you can keep a record of modules you install for your project.

一旦信息与您在此处看到的内容匹配,请按ENTER以完成此过程并创建package.json文件。 使用此文件,您可以记录为项目安装的模块。

Now that you have your package.json file, you can test out installing modules in the next step.

现在您有了package.json文件,可以在下一步中测试安装模块。

第2步-安装模块 (Step 2 — Installing Modules)

It is common in software development to use external libraries to perform ancillary tasks in projects. This allows the developer to focus on the business logic and create the application more quickly and efficiently.

在软件开发中,通常使用外部库在项目中执行辅助任务。 这使开发人员可以专注于业务逻辑并更快,更有效地创建应用程序。

For example, if our sample locator module has to make an external API request to get geographical data, we could use an HTTP library to make that task easier. Since our main goal is to return pertinent geographical data to the user, we could install a package that makes HTTP requests easier for us instead of rewriting this code for ourselves, a task that is beyond the scope of our project.

例如,如果我们的样本locator模块必须发出外部API请求以获取地理数据,则可以使用HTTP库来简化该任务。 由于我们的主要目标是将相关的地理数据返回给用户,因此我们可以安装一个使HTTP请求更轻松的软件包,而不是自己重写代码,而这是我们项目范围之外的任务。

Let’s run through this example. In your locator application, you will use the axios library, which will help you make HTTP requests. Install it by entering the following in your shell:

让我们来看这个例子。 在locator应用程序中,您将使用axios库,该库将帮助您发出HTTP请求。 在外壳程序中输入以下内容进行安装:

  • npm install axios --save

    npm install axios-保存

You begin this command with npm install, which will install the package (for brevity you can use npm i). You then list the packages that you want installed, separated by a space. In this case, this is axios. Finally, you end the command with the optional --save parameter, which specifies that axios will be saved as a project dependency.

您从npm install开始此命令,它将安装软件包(为简便起见,您可以使用npm i )。 然后,列出要安装的软件包,并用空格分隔。 在这种情况下,这是axios 。 最后,以可选的--save参数结束命令,该参数指定axios将另存为项目依赖项。

When the library is installed, you will see output similar to the following:

安装该库后,您将看到类似于以下的输出:


   
Output
... + axios@0.19.0 added 5 packages from 8 contributors and audited 5 packages in 0.764s found 0 vulnerabilities

Now, open the package.json file, using a text editor of your choice. This tutorial will use nano:

现在,使用您选择的文本编辑器打开package.json文件。 本教程将使用nano

  • nano package.json

    纳米package.json

You’ll see a new property, as highlighted in the following:

您将看到一个新属性,如下所示:

locator/package.json
locator / package.json
{
  "name": "locator",
  "version": "1.0.0",
  "description": "Finds the country of origin of the incoming request",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "ip",
    "geo",
    "country"
  ],
  "author": "Sammy sammy@your_domain (https://your_domain)",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.0"
  }
}

The --save option told npm to update the package.json with the module and version that was just installed. This is great, as other developers working on your projects can easily see what external dependencies are needed.

--save选项告诉npm使用刚刚安装的模块和版本更新package.json 。 很好,因为其他从事您项目的开发人员可以轻松查看需要哪些外部依赖项。

Note: You may have noticed the ^ before the version number for the axios dependency. Recall that semantic versioning consists of three digits: MAJOR, MINOR, and PATCH. The ^ symbol signifies that any higher MINOR or PATCH version would satisfy this version constraint. If you see ~ at the beginning of a version number, then only higher PATCH versions satisfy the constraint.

注意 :您可能已经注意到axios依赖项的版本号前面的^ 。 回想一下,语义版本控制由三个数字组成: MAJORMINORPATCH^符号表示任何更高的MINOR或PATCH版本都将满足此版本约束。 如果您在版本号的开头看到~ ,则只有更高的PATCH版本满足该约束。

When you are finished reviewing package.json, exit the file.

完成检查package.json ,退出文件。

开发依赖 (Development Dependencies)

Packages that are used for the development of a project but not for building or running it in production are called development dependencies. They are not necessary for your module or application to work in production, but may be helpful while writing the code.

用于项目开发而不用于在生产中构建或运行它的软件包称为开发依赖项 。 它们对于模块或应用程序在生产中的工作不是必需的,但是在编写代码时可能会有所帮助。

For example, it’s common for developers to use code linters to ensure their code follows best practices and to keep the style consistent. While this is useful for development, this only adds to the size of the distributable without providing a tangible benefit when deployed in production.

例如,对于开发人员而言,通常使用代码短绒来确保其代码遵循最佳实践并保持样式的一致性。 尽管这对开发很有用,但这只会增加可分发的大小,而在生产环境中部署时却不会带来明显的好处。

Install a linter as a development dependency for your project. Try this out in your shell:

安装一个linter作为您项目的开发依赖项。 在您的shell中尝试一下:

  • npm i eslint@6.0.0 --save-dev

    npm我eslint@6.0.0 --save-dev

In this command, you used the --save-dev flag. This will save eslint as a dependency that is only needed for development. Notice also that you added @6.0.0 to your dependency name. When modules are updated, they are tagged with a version. The @ tells npm to look for a specific tag of the module you are installing. Without a specified tag, npm installs the latest tagged version. Open package.json again:

在此命令中,您使用了--save-dev标志。 这会将eslint保存为仅开发所需的依赖项。 还要注意,您已将@6.0.0添加到依赖项名称中。 更新模块时,将使用版本标记它们。 @告诉npm查找要安装的模块的特定标签。 如果没有指定标签,npm将安装最新的标签版本。 再次打开package.json

  • nano package.json

    纳米package.json

This will show the following:

这将显示以下内容:

locator/package.json
locator / package.json
{
  "name": "locator",
  "version": "1.0.0",
  "description": "Finds the country of origin of the incoming request",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "ip",
    "geo",
    "country"
  ],
  "author": "Sammy sammy@your_domain (https://your_domain)",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.0"
  },
  "devDependencies": {
    "eslint": "^6.0.0"
  }
}

eslint has been saved as a devDependencies, along with the version number you specified earlier. Exit package.json.

eslint与先前指定的版本号一起另存为devDependencies 。 退出package.json

自动生成的文件: node_modulespackage-lock.json (Automatically Generated Files: node_modules and package-lock.json)

When you first install a package to a Node.js project, npm automatically creates the node_modules folder to store the modules needed for your project and the package-lock.json file that you examined earlier.

首次将软件包安装到Node.js项目时,npm会自动创建node_modules文件夹来存储项目所需的模块以及您之前检查过的package-lock.json文件。

Confirm these are in your working directory. In your shell, type ls and press ENTER. You will observe the following output:

确认它们在您的工作目录中。 在您的外壳中,键入ls ,然后按ENTER 。 您将观察到以下输出:


   
Output
node_modules package.json package-lock.json

The node_modules folder contains every installed dependency for your project. In most cases, you should not commit this folder into your version controlled repository. As you install more dependencies, the size of this folder will quickly grow. Furthermore, the package-lock.json file keeps a record of the exact versions installed in a more succinct way, so including node_modules is not necessary.

node_modules文件夹包含项目中每个已安装的依赖项。 在大多数情况下,你应该犯这个文件夹到您的版本控制库。 当您安装更多依赖项时,此文件夹的大小将快速增长。 此外, package-lock.json文件以更简洁的方式记录了安装的确切版本,因此不需要包括node_modules

While the package.json file lists dependencies that tell us the suitable versions that should be installed for the project, the package-lock.json file keeps track of all changes in package.json or node_modules and tells us the exact version of the package installed. You usually commit this to your version controlled repository instead of node_modules, as it’s a cleaner representation of all your dependencies.

package.json文件列出了告诉我们应该为项目安装的合适版本的依赖项,而package-lock.json文件则跟踪package.jsonnode_modules的所有更改,并告诉我们所安装软件包的确切版本。 您通常将其提交到版本控制的存储库中,而不是提交给node_modules ,因为它可以更清晰地表示所有依赖项。

从package.json安装 (Installing from package.json)

With your package.json and package-lock.json files, you can quickly set up the same project dependencies before you start development on a new project. To demonstrate this, move up a level in your directory tree and create a new folder named cloned_locator in the same directory level as locator:

使用package.jsonpackage-lock.json文件,可以在开始新项目开发之前快速设置相同的项目依赖项。 为了说明这一点,请在目录树中上cloned_locator ,并在与locator相同的目录级别中创建一个名为cloned_locator的新文件夹:

  • cd ..

    光盘..
  • mkdir cloned_locator

    mkdir cloned_locator

Move into your new directory:

移至新目录:

  • cd cloned_locator

    cd cloned_locator

Now copy the package.json and package-lock.json files from locator to cloned_locator:

现在,将locatorpackage.jsonpackage-lock.json文件复制到cloned_locator

  • cp ../locator/package.json ../locator/package-lock.json .

    cp ../locator/package.json ../locator/package-lock.json。

To install the required modules for this project, type:

要安装该项目所需的模块,请键入:

  • npm i

npm will check for a package-lock.json file to install the modules. If no lock file is available, it would read from the package.json file to determine the installations. It is usually quicker to install from package-lock.json, since the lock file contains the exact version of modules and their dependencies, meaning npm does not have to spend time figuring out a suitable version to install.

npm将检查package-lock.json文件以安装模块。 如果没有可用的锁定文件,它将从package.json文件中读取以确定安装。 通常,通过package-lock.json更快地进行安装,因为锁定文件包含模块及其依赖关系的确切版本,这意味着npm不必花费时间来确定合适的版本进行安装。

When deploying to production, you may want to skip the development dependencies. Recall that development dependencies are stored in the devDependencies section of package.json, and have no impact on the running of your app. When installing modules as part of the CI/CD process to deploy your application, omit the dev dependencies by running:

部署到生产环境时,您可能要跳过开发依赖项。 回想一下,开发依赖项存储在package.jsondevDependencies部分中,对应用程序的运行没有影响。 在CI / CD流程中安装模块以部署应用程序时,请通过运行以下命令忽略dev依赖项:

  • npm i --production

    npm我-生产

The --production flag ignores the devDependencies section during installation. For now, stick with your development build.

--production标志在安装过程中会忽略devDependencies部分。 现在,坚持使用您的开发版本。

Before moving to the next section, return to the locator folder:

移至下一部分之前,请返回locator文件夹:

  • cd ../locator

    cd ../定位器

全球安装 (Global Installations)

So far, you have been installing npm modules for the locator project. npm also allows you to install packages globally. This means that the package is available to your user in the wider system, like any other shell command. This ability is useful for the many Node.js modules that are CLI tools.

到目前为止,您已经为locator项目安装了npm模块。 npm还允许您全局安装软件包。 这意味着该软件包对于您的用户在更广泛的系统中都是可用的,就像其他任何shell命令一样。 此功能对于许多作为CLI工具的Node.js模块很有用。

For example, you may want to blog about the locator project that you’re currently working on. To do so, you can use a library like Hexo to create and manage your static website blog. Install the Hexo CLI globally like this:

例如,您可能想在博客上介绍当前正在处理的locator项目。 为此,您可以使用Hexo之类的库来创建和管理静态网站博客。 像这样全局安装Hexo CLI:

  • npm i hexo-cli -g

    npm我hexo-cli -g

To install a package globally, you append the -g flag to the command.

要全局安装软件包,请在命令后附加-g标志。

Note: If you get a permission error trying to install this package globally, your system may require super user privileges to run the command. Try again with sudo npm i hexo-cli -g.

注意 :如果在尝试全局安装此软件包时遇到权限错误,则系统可能需要超级用户特权才能运行该命令。 使用sudo npm i hexo-cli -g再试一次。

Test that the package was successfully installed by typing:

通过键入以下命令测试软件包是否已成功安装:

  • hexo --version

    十六进制版本

You will see output similar to:

您将看到类似于以下内容的输出:


   
Output
hexo-cli: 2.0.0 os: Linux 4.15.0-64-generic linux x64 http_parser: 2.7.1 node: 10.14.0 v8: 7.6.303.29-node.16 uv: 1.31.0 zlib: 1.2.11 ares: 1.15.0 modules: 72 nghttp2: 1.39.2 openssl: 1.1.1c brotli: 1.0.7 napi: 4 llhttp: 1.1.4 icu: 64.2 unicode: 12.1 cldr: 35.1 tz: 2019a

So far, you have learned how to install modules with npm. You can install packages to a project locally, either as a production or development dependency. You can also install packages based on pre-existing package.json or package-lock.json files, allowing you to develop with the same dependencies as your peers. Finally, you can use the -g flag to install packages globally, so you can access them regardless of whether you’re in a Node.js project or not.

到目前为止,您已经了解了如何使用npm安装模块。 您可以将软件包作为生产或开发依赖项本地安装到项目中。 您还可以基于预先存在的package.jsonpackage-lock.json文件安装软件包,从而使您可以使用与对等方相同的依赖项进行开发。 最后,您可以使用-g标志全局安装软件包,因此无论您是否在Node.js项目中,都可以访问它们。

Now that you can install modules, in the next section you will practice techniques to administer your dependencies.

现在您可以安装模块了,在下一节中,您将练习一些技巧来管理您的依赖项。

第3步-管理模块 (Step 3 — Managing Modules)

A complete package manager can do a lot more than install modules. npm has over 20 commands relating to dependency management available. In this step, you will:

一个完整的软件包管理器除了安装模块外,还可以做很多其他的事情。 npm提供了20多个与依赖项管理有关的命令。 在此步骤中,您将:

  • List modules you have installed.

    列出您已安装的模块。
  • Update modules to a more recent version.

    将模块更新到最新版本。
  • Uninstall modules you no longer need.

    卸载不再需要的模块。
  • Perform a security audit on your modules to find and fix security flaws.

    对模块执行安全审核,以发现并修复安全漏洞。

While these examples will be done in your locator folder, all of these commands can be run globally by appending the -g flag at the end of them, exactly like you did when installing globally.

尽管这些示例将在您的locator文件夹中完成,但是所有这些命令都可以通过在末尾附加-g标志来全局运行,就像在全局安装时所做的一样。

清单模块 (Listing Modules)

If you would like to know which modules are installed in a project, it would be easier to use the list or ls command instead of reading the package.json directly. To do this, enter:

如果您想知道项目中安装了哪些模块,那么使用listls命令而不是直接读取package.json会更容易。 为此,请输入:

  • npm ls

    npm ls

You will see output like this:

您将看到如下输出:


   
Output
├─┬ axios@0.19.0 │ ├─┬ follow-redirects@1.5.10 │ │ └─┬ debug@3.1.0 │ │ └── ms@2.0.0 │ └── is-buffer@2.0.3 └─┬ eslint@6.0.0 ├─┬ @babel/code-frame@7.5.5 │ └─┬ @babel/highlight@7.5.0 │ ├── chalk@2.4.2 deduped │ ├── esutils@2.0.3 deduped │ └── js-tokens@4.0.0 ├─┬ ajv@6.10.2 │ ├── fast-deep-equal@2.0.1 │ ├── fast-json-stable-stringify@2.0.0 │ ├── json-schema-traverse@0.4.1 │ └─┬ uri-js@4.2.2 ...

By default, ls shows the entire dependency tree—the modules your project depends on and the modules that your dependencies depend on. This can be a bit unwieldy if you want a high-level overview of what’s installed.

缺省情况下, ls显示整个依赖关系树,即项目所依赖的模块以及依赖项所依赖的模块。 如果您想大致了解所安装的内容,这可能会有些麻烦。

To only print the modules you installed without their dependencies, enter the following in your shell:

要仅打印没有依赖性的已安装模块,请在外壳程序中输入以下内容:

  • npm ls --depth 0

    npm ls-深度0

Your output will be:

您的输出将是:


   
Output
├── axios@0.19.0 └── eslint@6.0.0

The --depth option allows you to specify what level of the dependency tree you want to see. When it’s 0, you only see your top level dependencies.

--depth选项允许您指定要查看的依赖关系树的级别。 当它为0 ,您只会看到顶级依赖项。

更新模块 (Updating Modules)

It is a good practice to keep your npm modules up to date. This improves your likelihood of getting the latest security fixes for a module. Use the outdated command to check if any modules can be updated:

保持您的npm模块为最新是一个好习惯。 这增加了获得模块最新安全修复程序的可能性。 使用outdated命令检查是否可以更新任何模块:

  • npm outdated

    npm过时了

You will get output like the following:

您将获得如下输出:


   
Output
Package Current Wanted Latest Location eslint 6.0.0 6.7.1 6.7.1 locator

This command first lists the Package that’s installed and the Current version. The Wanted column shows which version satisfies your version requirement in package.json. The Latest column shows the most recent version of the module that was published.

该命令首先列出已安装的PackageCurrent版本。 Wanted列显示package.json中哪个版本满足您的版本要求。 Latest列显示已发布模块的最新版本。

The Location column states where in the dependency tree the package is located. The outdated command has the --depth flag like ls. By default, the depth is 0.

Location列指出程序包在依赖关系树中的位置。 outdated命令具有--depth标志,如ls 。 默认情况下,深度为0。

It seems that you can update eslint to a more recent version. Use the update or up command like this:

看来您可以将eslint更新为最新版本。 像这样使用updateup命令:

  • npm up eslint

    npm up eslint

The output of the command will contain the version installed:

该命令的输出将包含安装的版本:


   
Output
npm WARN locator@1.0.0 No repository field. + eslint@6.7.1 added 7 packages from 3 contributors, removed 5 packages, updated 19 packages, moved 1 package and audited 184 packages in 5.818s found 0 vulnerabilities

If you wanted to update all modules at once, then you would enter:

如果要一次更新所有模块,则输入:

  • npm up

    npm起来

卸载模块 (Uninstalling Modules)

The npm uninstall command can remove modules from your projects. This means the module will no longer be installed in the node_modules folder, nor will it be seen in your package.json and package-lock.json files.

npm uninstall命令可以从您的项目中删除模块。 这意味着该模块将不再安装在node_modules文件夹中,也不会在package.jsonpackage-lock.json文件中显示。

Removing dependencies from a project is a normal activity in the software development lifecycle. A dependency may not solve the problem as advertised, or may not provide a satisfactory development experience. In these cases, it may better to uninstall the dependency and build your own module.

从项目中删除依赖项是软件开发生命周期中的正常活动。 依赖关系可能无法解决所宣传的问题,或者可能无法提供令人满意的开发经验。 在这些情况下,最好卸载依赖项并构建自己的模块。

Imagine that axios does not provide the development experience you would have liked for making HTTP requests. Uninstall axios with the uninstall or un command by entering:

想象一下, axios无法提供您希望发出HTTP请求的开发经验。 通过输入以下命令,使用uninstallun命令卸载axios

  • npm un axios

    npm un axios

Your output will be similar to:

您的输出将类似于:


   
Output
npm WARN locator@1.0.0 No repository field. removed 5 packages and audited 176 packages in 1.488s found 0 vulnerabilities

It doesn’t explicitly say that axios was removed. To verify that it was uninstalled, list the dependencies once again:

它没有明确表示axios已被删除。 要验证它是否已卸载,请再次列出依赖性:

  • npm ls --depth 0

    npm ls-深度0

Now, we only see that eslint is installed:

现在,我们只看到eslint已安装:


   
Output
└── eslint@6.7.1

This shows that you have successfully uninstalled the axios package.

这表明您已经成功卸载了axios软件包。

审核模块 (Auditing Modules)

npm provides an audit command to highlight potential security risks in your dependencies. To see the audit in action, install an outdated version of the request module by running the following:

npm提供了一个audit命令,以突出显示依赖项中的潜在安全风险。 要查看实际的审核,请通过运行以下命令安装请求模块的过时版本:

  • npm i request@2.60.0

    npm我request@2.60.0

When you install this outdated version of request, you’ll notice output similar to the following:

安装request此过时版本时,您会注意到类似于以下内容的输出:


   
Output
+ request@2.60.0 added 54 packages from 49 contributors and audited 243 packages in 7.26s found 6 moderate severity vulnerabilities run `npm audit fix` to fix them, or `npm audit` for details

npm is telling you that you have vulnerabilities in your dependencies. To get more details, audit your entire project with:

npm告诉您,您的依赖项中存在漏洞。 要获取更多详细信息,请使用以下方法审计整个项目:

  • npm audit

    npm审核

The audit command shows tables of output highlighting security flaws:

audit命令显示输出表,突出显示安全漏洞:


   
Output
=== npm audit security report === # Run npm install request@2.88.0 to resolve 1 vulnerability ┌───────────────┬──────────────────────────────────────────────────────────────┐ │ Moderate │ Memory Exposure │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ Package │ tunnel-agent │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ Dependency of │ request │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ Path │ request > tunnel-agent │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ More info │ https://npmjs.com/advisories/598 │ └───────────────┴──────────────────────────────────────────────────────────────┘ # Run npm update request --depth 1 to resolve 1 vulnerability ┌───────────────┬──────────────────────────────────────────────────────────────┐ │ Moderate │ Remote Memory Exposure │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ Package │ request │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ Dependency of │ request │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ Path │ request │ ├───────────────┼──────────────────────────────────────────────────────────────┤ │ More info │ https://npmjs.com/advisories/309 │ └───────────────┴──────────────────────────────────────────────────────────────┘ ...

You can see the path of the vulnerability, and sometimes npm offers ways for you to fix it. You can run the update command as suggested, or you can run the fix subcommand of audit. In your shell, enter:

您可以看到该漏洞的路径,有时npm提供了一些修复方法。 您可以按照建议运行update命令,也可以运行auditfix子命令。 在您的外壳中,输入:

  • npm audit fix

    npm审核修复

You will see similar output to:

您将看到类似的输出:


   
Output
+ request@2.88.0 added 19 packages from 24 contributors, removed 32 packages and updated 12 packages in 6.223s fixed 2 of 6 vulnerabilities in 243 scanned packages 4 vulnerabilities required manual review and could not be updated

npm was able to safely update two of the packages, decreasing your vulnerabilities by the same amount. However, you still have four vulnerabilities in your dependencies. The audit fix command does not always fix every problem. Although a version of a module may have a security vulnerability, if you update it to a version with a different API then it could break code higher up in the dependency tree.

npm能够安全地更新其中两个软件包,从而将您的漏洞减少了相同数量。 但是,您的依赖项中仍然存在四个漏洞。 audit fix命令并不总是能解决所有问题。 尽管模块的某个版本可能存在安全漏洞,但是如果将其更新为使用其他API的版本,则它可能会将代码分解成更高的依赖树。

You can use the --force parameter to ensure the vulnerabilities are gone, like this:

您可以使用--force参数来确保漏洞消失,如下所示:

  • npm audit fix --force

    npm审核修复--force

As mentioned before, this is not recommended unless you are sure that it won’t break functionality.

如前所述,除非您确定它不会破坏功能,否则不建议这样做。

结论 (Conclusion)

In this tutorial, you went through various exercises to demonstrate how Node.js modules are organized into packages, and how these packages are managed by npm. In a Node.js project, you used npm packages as dependencies by creating and maintaining a package.json file—a record of your project’s metadata, including what modules you installed. You also used the npm CLI tool to install, update, and remove modules, in addition to listing the dependency tree for your projects and checking and updating modules that are outdated.

在本教程中,您进行了各种练习,以演示如何将Node.js模块组织到程序包中,以及如何由npm管理这些程序包。 在Node.js项目中,通过创建和维护package.json文件(项目的元数据记录,包括安装的模块),将npm软件包用作依赖项。 除了列出项目的依赖关系树以及检查和更新过时的模块之外,您还使用npm CLI工具安装,更新和删除模块。

In the future, leveraging existing code by using modules will speed up development time, as you don’t have to repeat functionality. You will also be able to create your own npm modules, and these will in turn will be managed by others via npm commands. As for next steps, experiment with what you learned in this tutorial by installing and testing the variety of packages out there. See what the ecosystem provides to make problem solving easier. For example, you could try out TypeScript, a superset of JavaScript, or turn your website into mobile apps with Cordova. If you’d like to learn more about Node.js, see our other Node.js tutorials.

将来,通过使用模块来利用现有代码将加快开发时间,因为您不必重复功能。 您还可以创建自己的npm模块,而这些模块又将由其他人通过npm命令进行管理。 至于后续步骤,请通过安装和测试各种软件包来试验您在本教程中学到的知识。 看看生态系统提供了什么,使解决问题变得更加容易。 例如,您可以试用TypeScript (JavaScript的超集),或者使用Cordova将您的网站转换为移动应用程序。 如果您想了解有关Node.js的更多信息,请参阅我们的其他Node.js教程 。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-node-js-modules-with-npm-and-package-json


http://www.niftyadmin.cn/n/3649391.html

相关文章

Android系统获取手机型号和系统版本号,以及其他配置信息

<pre name"code" class"java">String sdkandroid.os.Build.VERSION.SDK; // SDK号 String modelandroid.os.Build.MODEL; // 手机型号 String releaseandroid.os.Build.VERSION.RELEASE; // android系统版本号执行以下代码前&#xff0c;须在manifes…

网页模块实现电脑端显示(隐藏)手机端隐藏(显示)

在开发的很多时候&#xff0c;遇到有些模块在电脑端显示正常&#xff0c;而到手机端就显示不正常&#xff0c;或者有些模块只想在电脑或手机一端显示。另一端不显示。这个就要用到HTMLCSS的隐藏功能了。 1、电脑端显示&#xff0c;手机端隐藏&#xff0c;以下是CSS样式&#xf…

赵勖予:再见,CodeArtist(下)

Lee感到穷途末路。根据国家信息产业部当年的统计数字&#xff0c;我国IT行业的人才需求每年增加一百万&#xff0c;而这一百万中竟然没有单片机天才Lee的一个位置。激愤之下他甚至打算回安阳钢厂&#xff0c;再去做他的弱电工人&#xff0c;但世上又哪有如此好走的回头路&#…

5分钟即可开始视觉测试

介绍 (Introduction) There are tons of tools out there that help you make sure your app is functioning perfectly, but how do you catch bugs that are purely visual? 有大量工具可帮助您确保应用程序正常运行&#xff0c;但是如何捕获纯可视化的错误&#xff1f; In…

WordPress自定义代码实现圆角彩色标签云

WordPress默认的标签云是黑白的&#xff0c;博主使用的DUX主题的标签云虽然有颜色&#xff0c;但是也不是彩色的。所以想到了自定义代码实现圆角彩色标签云。 使用方法&#xff1a;在当前主题目录下面的functions.php里面加入以下代码&#xff1a; //圆角背景色标签 function c…

自定义view-绘制统计图

效果图如下: 主要代码&#xff1a; public class MyTestView extends View { private Paint mPaint; private static final String title "2013-2017上半年的销售情况"; private static final String content "来自公司销售的统计数据"; public MyTe…

怎么计算apk的启动时间?

利用python或者直接用adb命令怎么计算apk的启动时间呢&#xff1f;就是计算从点击图标到apk完全启动所花费的时间。比如&#xff0c;对游戏来说就是点击游戏图标到进入到登录界面的这段时间。 已知的两种方法貌似可以获取&#xff0c;但是感觉结果不准确&#xff1a;一种是&…

如何在Ubuntu 18.04上安装和使用TimescaleDB

The author selected the Computer History Museum to receive a donation as part of the Write for DOnations program. 作者选择“ 计算机历史博物馆”作为“ Write for DOnations”计划的一部分接受捐赠。 介绍 (Introduction) Many applications, such as monitoring sys…