当前位置: 首页 > 工具软件 > Colors.js > 使用案例 >

node.js 模块_如何创建Node.js模块

龙俭
2023-12-01

node.js 模块

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)

In Node.js, a module is a collection of JavaScript functions and objects that can be used by external applications. Describing a piece of code as a module refers less to what the code is and more to what it does—any Node.js file or collection of files can be considered a module if its functions and data are made usable to external programs.

在Node.js中, 模块是可由外部应用程序使用JavaScript函数和对象的集合。 将一段代码描述为模块意味着更少的是什么代码,而更多的是它的功能-如果任何Node.js文件或文件集合可以使其功能和数据可用于外部程序,则可以将其视为模块。

Because modules provide units of functionality that can be reused in many larger programs, they enable you to create loosely coupled applications that scale with complexity, and open the door for you to share your code with other developers. Being able to write modules that export useful functions and data will allow you to contribute to the wider Node.js community—in fact, all packages that you use on npm were bundled and shared as modules. This makes creating modules an essential skill for a Node.js developer.

因为模块提供了可以在许多大型程序中重用的功能单元,所以它们使您能够创建松散耦合的应用程序,这些应用程序可以随着复杂性而扩展,并为您与其他开发人员共享代码打开了大门。 能够编写导出有用功能和数据的模块将使您能够为更广泛的Node.js社区做出贡献-实际上,您在npm上使用的所有软件包都捆绑并共享为模块。 这使得创建模块成为Node.js开发人员的一项基本技能。

In this tutorial, you will create a Node.js module that suggests what color web developers should use in their designs. You will develop the module by storing the colors as an array, and providing a function to retrieve one randomly. Afterwards, you will run through various ways of importing a module into a Node.js application.

在本教程中,您将创建一个Node.js模块,该模块建议Web开发人员在设计中应使用什么颜色。 您将通过将颜色存储为数组并提供随机检索颜色的功能来开发模块。 之后,您将通过各种方式将模块导入Node.js应用程序。

先决条件 (Prerequisites)

第1步-创建模块 (Step 1 — Creating a Module)

This step will guide you through creating your first Node.js module. Your module will contain a collection of colors in an array and provide a function to get one at random. You will use the Node.js built-in exports property to make the function and array available to external programs.

此步骤将指导您创建第一个Node.js模块。 您的模块将在数组中包含一组颜色,并提供一种随机获取颜色的功能。 您将使用Node.js内置的exports属性使函数和数组可用于外部程序。

First, you’ll begin by deciding what data about colors you will store in your module. Every color will be an object that contains a name property that humans can easily identify, and a code property that is a string containing an HTML color code. HTML color codes are six-digit hexadecimal numbers that allow you to change the color of elements on a web page. You can learn more about HTML color codes by reading this HTML Color Codes and Names article.

首先,首先要确定要存储在模块中的有关颜色的数据。 每种颜色都是一个对象,其中包含人类可以轻松识别的name属性,以及一个code属性,该属性是包含HTML颜色代码的字符串。 HTML颜色代码是六位十六进制数字,使您可以更改网页上元素的颜色。 您可以阅读此HTML颜色代码和名称文章,以了解有关HTML颜色代码的更多信息。

You will then decide what colors you want to support in your module. Your module will contain an array called allColors that will contain six colors. Your module will also include a function called getRandomColor() that will randomly select a color from your array and return it.

然后,您将决定要在模块中支持的颜色。 您的模块将包含一个名为allColors的数组,该数组将包含六种颜色。 您的模块还将包含一个名为getRandomColor()的函数,该函数将从数组中随机选择一种颜色并将其返回。

In your terminal, make a new folder called colors and move into it:

在您的终端中,新建一个名为colors文件夹并移至其中:

  • mkdir colors

    mkdir颜色
  • cd colors

    cd颜色

Initialize npm so other programs can import this module later in the tutorial:

初始化npm,以便其他程序可以在本教程的后面部分中导入此模块:

  • npm init -y

    npm初始化-y

You used the -y flag to skip the usual prompts to customize your package.json. If this were a module you wished to publish to npm, you would answer all these prompts with relevant data, as explained in How To Use Node.js Modules with npm and package.json.

您使用了-y标志来跳过通常的提示来定制package.json 。 如果这是您希望发布到npm的模块,那么您将使用相关数据回答所有这些提示,如如何将Node.js模块与npm和package.json一起使用中所述

In this case, your output will be:

在这种情况下,您的输出将是:


   
   
Output
{ "name": "colors", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }

Now, open up a command-line text editor such as nano and create a new file to serve as the entry point for your module:

现在,打开命令行文本编辑器(例如nano并创建一个新文件作为模块的入口点:

  • nano index.js

    纳米index.js

Your module will do a few things. First, you’ll define a Color class. Your Color class will be instantiated with its name and HTML code. Add the following lines to create the class:

您的模块将执行一些操作。 首先,您将定义一个Color 。 您的Color类将使用其名称和HTML代码实例化。 添加以下行以创建类:

~/colors/index.js
〜/ colors / index.js
class Color {
  constructor(name, code) {
    this.name = name;
    this.code = code;
  }
}

Now that you have your data structure for Color, add some instances into your module. Write the following highlighted array to your file:

现在您有了Color的数据结构,将一些实例添加到模块中。 将以下突出显示的数组写入文件:

~/colors/index.js
〜/ colors / index.js
class Color {
  constructor(name, code) {
    this.name = name;
    this.code = code;
  }
}

const allColors = [
  new Color('brightred', '#E74C3C'),
  new Color('soothingpurple', '#9B59B6'),
  new Color('skyblue', '#5DADE2'),
  new Color('leafygreen', '#48C9B0'),
  new Color('sunkissedyellow', '#F4D03F'),
  new Color('groovygray', '#D7DBDD'),
];

Finally, enter a function that randomly selects an item from the allColors array you just created:

最后,输入一个函数 ,从刚创建的allColors数组中随机选择一个项目:

~/colors/index.js
〜/ colors / index.js
class Color {
  constructor(name, code) {
    this.name = name;
    this.code = code;
  }
}

const allColors = [
  new Color('brightred', '#E74C3C'),
  new Color('soothingpurple', '#9B59B6'),
  new Color('skyblue', '#5DADE2'),
  new Color('leafygreen', '#48C9B0'),
  new Color('sunkissedyellow', '#F4D03F'),
  new Color('groovygray', '#D7DBDD'),
];

exports.getRandomColor = () => {
  return allColors[Math.floor(Math.random() * allColors.length)];
}

exports.allColors = allColors;

The exports keyword references a global object available in every Node.js module. All functions and objects stored in a module’s exports object are exposed when other Node.js modules import it. The getRandomColor() function was created directly on the exports object, for example. You then added an allColors property to the exports object that references the local constant allColors array created earlier in the script.

exports关键字引用每个Node.js模块中可用的全局对象。 当其他Node.js模块导入它时,将公开存储在模块的exports对象中的所有函数和对象。 例如,直接在exports对象上创建了getRandomColor()函数。 然后,您将allColors属性添加到了exports对象,该属性引用了脚本前面创建的局部常量allColors数组。

When other modules import this module, both allColors and getRandomColor() will be exposed and available for usage.

当其他模块导入该模块时, allColorsgetRandomColor()都将公开并可以使用。

Save and exit the file.

保存并退出文件。

So far, you have created a module that contains an array of colors and a function that returns one randomly. You have also exported the array and function, so that external programs can use them. In the next step, you will use your module in other applications to demonstrate the effects of export.

到目前为止,您已经创建了一个模块,该模块包含一个颜色数组和一个随机返回一个颜色的函数。 您还导出了数组和函数,以便外部程序可以使用它们。 在下一步中,您将在其他应用程序中使用您的模块来演示export的效果。

第2步-使用REPL测试模块 (Step 2 — Testing your Module with the REPL)

Before you build a complete application, take a moment to confirm that your module is working. In this step, you will use the REPL to load the colors module. While in the REPL, you will call the getRandomColor() function to see if it behaves as you expect it to.

在构建完整的应用程序之前,请花一点时间确认模块是否正常工作。 在此步骤中,您将使用REPL加载colors模块。 在REPL中时,将调用getRandomColor()函数以查看其行为是否符合您的预期。

Start the Node.js REPL in the same folder as the index.js file:

在与index.js文件相同的文件夹中启动Node.js REPL:

  • node

    节点

When the REPL has started, you will see the > prompt. This means you can enter JavaScript code that will be immediately evaluated. If you would like to read more about this, follow our guide on using the REPL.

REPL启动后,您将看到>提示符。 这意味着您可以输入将立即评估JavaScript代码。 如果您想了解更多有关此的信息,请遵循我们的使用REPL指南。

First, enter the following:

首先,输入以下内容:

  • colors = require('./index');

    颜色= require('./ index');

In this command, require() loads the colors module at its entry point. When you press ENTER you will get:

在此命令中, require()在其入口点加载colors模块。 当您按ENTER您将得到:


   
   
Output
{ getRandomColor: [Function], allColors: [ Color { name: 'brightred', code: '#E74C3C' }, Color { name: 'soothingpurple', code: '#9B59B6' }, Color { name: 'skyblue', code: '#5DADE2' }, Color { name: 'leafygreen', code: '#48C9B0' }, Color { name: 'sunkissedyellow', code: '#F4D03F' }, Color { name: 'groovygray', code: '#D7DBDD' } ] }

The REPL shows us the value of colors, which are all the functions and objects imported from the index.js file. When you use the require keyword, Node.js returns all the contents within the exports object of a module.

REPL向我们显示colors的值,这些值是从index.js文件导入的所有函数和对象。 使用require关键字时,Node.js返回模块exports对象中的所有内容。

Recall that you added getRandomColor() and allColors to exports in the colors module. For that reason, you see them both in the REPL when they are imported.

回想一下,您在colors模块allColors getRandomColor()allColors添加到了exports中。 因此,导入它们时,您会在REPL中看到它们。

At the prompt, test the getRandomColor() function:

在提示符下,测试getRandomColor()函数:

  • colors.getRandomColor();

    colors.getRandomColor();

You’ll be prompted with a random color:

系统会提示您使用随机颜色:


   
   
Output
Color { name: 'groovygray', code: '#D7DBDD' }

As the index is random, your output may vary. Now that you confirmed that the colors module is working, exit the Node.js REPL:

由于索引是随机的,因此您的输出可能会有所不同。 现在,您已经确认colors模块正在运行,请退出Node.js REPL:

  • .exit

    。出口

This will return you to your terminal command line.

这将使您返回到终端命令行。

You have just confirmed that your module works as expected using the REPL. Next, you will apply these same concepts and load your module into an application, as you would do in a real project.

您刚刚确认使用REPL,您的模块可以正常工作。 接下来,您将应用这些相同的概念并将模块加载到应用程序中,就像在真实项目中一样。

步骤3 —将本地模块保存为依赖项 (Step 3 — Saving your Local Module as a Dependency)

While testing your module in the REPL, you imported it with a relative path. This means you used the location of the index.js file in relation to the working directory to get its contents. While this works, it is usually a better programming experience to import modules by their names so that the import is not broken when the context is changed. In this step, you will install the colors module with npm’s local module install feature.

在REPL中测试模块时,您使用相对路径导入了它。 这意味着您使用index.js文件相对于工作目录的位置来获取其内容。 在这种情况下,按模块名称导入模块通常是更好的编程体验,这样在更改上下文时不会中断导入。 在此步骤中,您将使用npm的本地模块install功能安装colors模块。

Set up a new Node.js module outside the colors folder. First, go to the previous directory and create a new folder:

colors文件夹外设置一个新的Node.js模块。 首先,转到上一个目录并创建一个新文件夹:

  • cd ..

    光盘..
  • mkdir really-large-application

    mkdir大型应用程序

Now move into your new project:

现在进入新项目:

  • cd really-large-application

    cd真正大应用

Like with the colors module, initialize your folder with npm:

colors模块一样,使用npm初始化文件夹:

  • npm init -y

    npm初始化-y

The following package.json will be generated:

将生成以下package.json


   
   
Output
{ "name": "really-large-application", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }

Now, install your colors module and use the --save flag so it will be recorded in your package.json file:

现在,安装您的colors模块并使用--save标志,以便将其记录在package.json文件中:

  • npm install --save ../colors

    npm install-保存../colors

You just installed your colors module in the new project. Open the package.json file to see the new local dependency:

您刚刚在新项目中安装了colors模块。 打开package.json文件以查看新的本地依赖项:

  • nano package.json

    纳米package.json

You will find that the following highlighted lines have been added:

您会发现已添加以下突出显示的行:

~/really-large-application/package.json
〜/ really-large-application / package.json
{
  "name": "really-large-application",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "colors": "file:../colors"
  }
}

Exit the file.

退出文件。

The colors module was copied to your node_modules directory. Verify it’s there with the following command:

colors模块已复制到您的node_modules目录。 使用以下命令验证其是否存在:

  • ls node_modules

    ls node_modules

This will give the following output:

这将给出以下输出:


   
   
Output
colors

Use your installed local module in this new program. Re-open your text editor and create another JavaScript file:

在此新程序中使用已安装的本地模块。 重新打开您的文本编辑器并创建另一个JavaScript文件:

  • nano index.js

    纳米index.js

Your program will first import the colors module. It will then choose a color at random using the getRandomColor() function provided by the module. Finally, it will print a message to the console that tells the user what color to use.

您的程序将首先导入colors模块。 然后,它将使用模块提供的getRandomColor()函数随机选择一种颜色。 最后,它将向控制台打印一条消息,告诉用户要使用哪种颜色。

Enter the following code in index.js:

index.js输入以下代码:

~/really-large-application/index.js
〜/ really-large-application / index.js
const colors = require('colors');

const chosenColor = colors.getRandomColor();
console.log(`You should use ${chosenColor.name} on your website. It's HTML code is ${chosenColor.code}`);

Save and exit this file.

保存并退出该文件。

Your application will now tell the user a random color option for a website component.

您的应用程序现在将告诉用户网站组件的随机颜色选项。

Run this script with:

使用以下命令运行此脚本:

  • node index.js

    节点index.js

Your output will be similar to:

您的输出将类似于:


   
   
Output
You should use leafygreen on your website. It's HTML code is #48C9B0

You’ve now successfully installed the colors module and can manage it like any other npm package used in your project. However, if you added more colors and functions to your local colors module, you would have to run npm update in your applications to be able to use the new options. In the next step, you will use the local module colors in another way and get automatic updates when the module code changes.

现在,您已经成功安装了colors模块,并且可以像项目中使用的任何其他npm软件包一样对其进行管理。 但是,如果您在本地colors模块中添加了更多的颜色和功能,则必须在应用程序中运行npm update才能使用新选项。 在下一步中,您将以另一种方式使用本地模块colors ,并在模块代码更改时获得自动更新。

步骤4 —链接本地模块 (Step 4 — Linking a Local Module)

If your local module is in heavy development, continually updating packages can be tedious. An alternative would be to link the modules. Linking a module ensures that any updates to the module are immediately reflected in the applications using it.

如果您的本地模块正在进行繁重的开发,则不断更新软件包可能很乏味。 另一种方法是链接模块。 链接模块可确保对模块的任何更新均立即反映在使用该模块的应用程序中。

In this step, you will link the colors module to your application. You will also modify the colors module and confirm that its most recent changes work in the application without having to reinstall or upgrade.

在此步骤中,您将把colors模块链接到您的应用程序。 您还将修改colors模块并确认其最新更改在应用程序中有效,而无需重新安装或升级。

First, uninstall your local module:

首先,卸载本地模块:

  • npm un colors

    npm联合国颜色

npm links modules by using symbolic links (or symlinks), which are references that point to files or directories in your computer. Linking a module is done in two steps:

npm通过使用符号链接 (或符号链接)链接模块, 符号链接是指向计算机中文件或目录的引用。 链接模块分两个步骤完成:

  1. Creating a global link to the module. npm creates a symlink between your global node_modules directory and the directory of your module. The global node_modules directory is the location in which all your system-wide npm packages are installed (any package you install with the -g flag).

    创建到模块的全局链接 。 npm在全局node_modules目录和模块目录之间创建符号链接。 全局node_modules目录是所有系统级npm软件包(使用-g标志安装的任何软件包)的安装位置。

  2. Create a local link. npm creates a symlink between your local project that’s using the module and the global link of the module.

    创建本地链接 。 npm在使用该模块的本地项目与该模块的全局链接之间创建符号链接。

First, create the global link by returning to the colors folder and using the link command:

首先,通过返回colors文件夹并使用link命令来创建全局链接:

  • cd ../colors

    cd ../ colors
  • sudo npm link

    sudo npm链接

Once complete, your shell will output:

完成后,您的shell将输出:


   
   
Output
/usr/local/lib/node_modules/colors -> /home/sammy/colors

You just created a symlink in your node_modules folder to your colors directory.

您刚刚在node_modules文件夹中创建了一个node_modules colors目录的符号链接。

Return to the really-large-application folder and link the package:

返回到really-large-application文件夹并链接该包:

  • cd ../really-large-application

    cd ../really-large-application
  • sudo npm link colors

    sudo npm链接颜色

You will receive output similar to the following:

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


   
   
Output
/home/sammy/really-large-application/node_modules/colors -> /usr/local/lib/node_modules/colors -> /home/sammy/colors

Note: If you would like to type a bit less, you can use ln instead of link. For example, npm ln colors would have worked the exact same way.

注意 :如果您想少键入一些,可以使用ln代替link 。 例如, npm ln colors将以完全相同的方式工作。

As the output shows, you just created a symlink from your really-large-application’s local node_modules directory to the colors symlink in your global node_modules, which points to the actual directory with the colors module.

如输出所示,您刚刚从really-large-application的本地node_modules目录创建了一个符号链接,然后创建了全局node_modulescolors符号链接,该符号链接指向colors模块的实际目录。

The linking process is complete. Run your file to ensure it still works:

链接过程完成。 运行文件以确保其仍然有效:

  • node index.js

    节点index.js

Your output will be similar to:

您的输出将类似于:


   
   
Output
You should use sunkissedyellow on your website. It's HTML code is #F4D03F

Your program functionality is intact. Next, test that updates are immediately applied. In your text editor, re-open the index.js file in the colors module:

您的程序功能是完整的。 接下来,测试是否立即应用了更新。 在您的文本编辑器中,重新打开colors模块中的index.js文件:

  • cd ../colors

    cd ../ colors
  • nano index.js

    纳米index.js

Now add a function that selects the very best shade of blue that exists. It takes no arguments, and always returns the third item of the allColors array. Add these lines to the end of the file:

现在添加一个功能,选择存在的最佳蓝色阴影。 它不带任何参数,并且始终返回allColors数组的第三项。 将这些行添加到文件末尾:

~/colors/index.js
〜/ colors / index.js
class Color {
  constructor(name, code) {
    this.name = name;
    this.code = code;
  }
}

const allColors = [
  new Color('brightred', '#E74C3C'),
  new Color('soothingpurple', '#9B59B6'),
  new Color('skyblue', '#5DADE2'),
  new Color('leafygreen', '#48C9B0'),
  new Color('sunkissedyellow', '#F4D03F'),
  new Color('groovygray', '#D7DBDD'),
];

exports.getRandomColor = () => {
        return allColors[Math.floor(Math.random() * allColors.length)];
        }

exports.allColors = allColors;

exports.getBlue = () => {
  return allColors[2];
}

Save and exit the file, then re-open the index.js file in the really-large-application folder:

保存并退出文件,然后在really-large-application文件夹中重新打开index.js文件:

  • cd ../really-large-application

    cd ../really-large-application
  • nano index.js

    纳米index.js

Make a call to the newly created getBlue() function, and print a sentence with the color’s properties. Add these statements to the end of the file:

调用新创建的getBlue()函数,并打印具有颜色属性的句子。 将这些语句添加到文件末尾:

~/really-large-application/index.js
〜/ really-large-application / index.js
const colors = require('colors');

const chosenColor = colors.getRandomColor();
console.log(`You should use ${chosenColor.name} on your website. It's HTML code is ${chosenColor.code}`);

const favoriteColor = colors.getBlue();
console.log(`My favorite color is ${favoriteColor.name}/${favoriteColor.code}, btw`);

Save and exit the file.

保存并退出文件。

The code now uses the newly create getBlue() function. Execute the file as before:

该代码现在使用新创建的getBlue()函数。 像以前一样执行文件:

  • node index.js

    节点index.js

You will get output like:

您将获得如下输出:


   
   
Output
You should use brightred on your website. It's HTML code is #E74C3C My favorite color is skyblue/#5DADE2, btw

Your script was able to use the latest function in your colors module, without having to run npm update. This will make it easier to make changes to this application in development.

您的脚本能够使用colors模块中的最新功能,而无需运行npm update 。 这将使在开发中对该应用程序进行更改变得更加容易。

As you write larger and more complex applications, think about how related code can be grouped into modules, and how you want these modules to be set up. If your module is only going to be used by one program, it can stay within the same project and be referenced by a relative path. If your module will later be shared separately or exists in a very different location from the project you are working on now, installing or linking might be more viable. Modules in active development also benefit from the automatic updates of linking. If the module is not under active development, using npm install may be the easier option.

在编写更大,更复杂的应用程序时,请考虑如何将相关代码分组到模块中,以及如何设置这些模块。 如果您的模块仅由一个程序使用,则它可以保留在同一项目中,并由相对路径引用。 如果您的模块以后将被单独共享或与您现在正在处理的项目位于不同的位置,则安装或链接可能更可行。 主动开发中的模块还受益于链接的自动更新。 如果该模块未处于主动开发中,则使用npm install可能是更简单的选择。

结论 (Conclusion)

In this tutorial, you learned that a Node.js module is a JavaScript file with functions and objects that can be used by other programs. You then created a module and attached your functions and objects to the global exports object to make them available to external programs. Finally, you imported that module into a program, demonstrating how modules come together into larger applications.

在本教程中,您了解到Node.js模块是一个JavaScript文件,其中包含可被其他程序使用的函数和对象。 然后,您创建了一个模块,并将函数和对象附加到全局exports对象,以使它们可用于外部程序。 最后,您将该模块导入到程序中,演示了模块如何组合成更大的应用程序。

Now that you know how to create modules, think about the type of program you want to write and break it down into various components, keeping each unique set of activities and data in their own modules. The more practice you get writing modules, the better your ability to write quality Node.js programs on your learning journey. To work through an example of a Node.js application that uses modules, see our How To Set Up a Node.js Application for Production on Ubuntu 18.04 tutorial.

现在您已经知道如何创建模块,请考虑要编写的程序类型并将其分解为各个组件,将每个唯一的活动集和数据保留在各自的模块中。 编写模块的实践越多,在学习过程中编写高质量Node.js程序的能力就越高。 要查看使用模块的Node.js应用程序的示例,请参阅我们的《 如何在Ubuntu 18.04上为生产设置Node.js应用程序》教程。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-create-a-node-js-module

node.js 模块

 类似资料: