Node.js NPM Tutorial: Create, Publish, Extend & Manage

PrimerPlus發表於2020-05-23

A module in Node.js is a logical encapsulation of code in a single unit. It's always a good programming practice to always segregate code in such a way that makes it more manageable and maintainable for future purposes. That's where modules in Node.js comes in action.

Since each module is an independent entity with its own encapsulated functionality, it can be managed as a separate unit of work.

由於每個模組都是具有其自身封裝功能的獨立實體,因此可以將其作為單獨的工作單元進行管理

In this tutorial, will learn-

What are modules in Node.js?

As stated earlier, modules in Node.js are a way of encapsulating code in a separate logical unit. There are many ready made modules available in the market which can be used within Node.js.

如前所述,Node.js中的模組是一種將程式碼封裝在單獨的邏輯單元中的方法。市場上有很多現成的模組可以在Node.js中使用。

Below are some of the popular modules which are used in a Node.js application

  1. Express framework – Express is a minimal and flexible Node.js web application framework that provides a robust set of features for the web and mobile applications.

    Express是一個最小且靈活的Node.js Web應用程式框架,為Web和移動應用程式提供了一組強大的功能

  2. Socket.io - Socket.IO enables real-time bidirectional event-based communication. This module is good for creation of chatting based applications.

    Socket.IO支援基於事件的實時雙向通訊。該模組非常適合建立基於聊天的應用程式

  3. Pug - Pug is a high-performance template engine and implemented with JavaScript for node and browsers.

    Pug是一種高效能的模板引擎,並使用JavaScript實現了針對node和瀏覽器的功能

  4. MongoDB - The MongoDB Node.js driver is the officially supported node.js driver for MongoDB.

    MongoDB Node.js驅動程式是MongoDB官方支援的node.js驅動程式。

  5. Restify - restify is a lightweight framework, similar to express for building REST APIs

    restify是一個輕量級框架,類似於用於構建REST API的表達

  6. Bluebird - Bluebird is a fully-featured promise library with a focus on innovative features and performance

Using modules in Node.js

In order to use modules in a Node.js application, they first need to be installed using the Node package manager.

為了在Node.js應用程式中使用模組,首先需要使用Node軟體包管理器來安裝它們。下面的命令列顯示瞭如何安裝“ express”模組。

The below command line shows how a module "express" can be installed.

npm install express

  • The above command will download the necessary files which contain the "express modules" and take care of the installation as well

    上面的命令將下載包含“ express modules”的必要檔案,並負責安裝

  • Once the module has been installed, in order to use a module in a Node.js application, you need to use the 'require' keyword. This keyword is a way that Node.js uses to incorporate the functionality of a module in an application.

    安裝模組後,為了在Node.js應用程式中使用模組,您需要使用'require'關鍵字。此關鍵字是Node.js用於在應用程式中合併模組功能的一種方式

    Let's look at an example of how we can use the "require" keyword. The below "Guru99" code example shows how to use the require function

    讓我們看一個示例,說明如何使用“ require”關鍵字。下面的“ Guru99”程式碼示例顯示瞭如何使用require函式

    注意在寫程式碼時var應改為const

    const express = require('express');
    const app = express();
    
    app.set('view engine','pug');
    app.get('/',function(req,res) {
    });
    const server = app.listen(3000,function() {
    });
    
1. In the first statement itself, we are using the "require" keyword to include the express module. The "express" module is an optimized JavaScript library for Node.js development. This is one of the most commonly used Node.js modules.
在第一個語句本身中,我們使用“ require”關鍵字來包含Express模組。“ express”模組是用於Node.js開發的優化的JavaScript庫。這是最常用的Node.js模組之一
  
2. After the module is included, in order to use the functionality within the module, an object needs to be created. Here an object of the express module is created.
包含模組後,為了使用模組內的功能,需要建立一個物件。此處建立了Express模組的物件。
  
3. Once the module is included using the "require" command and an "object" is created, the required methods of the express module can be invoked. Here we are using the set command to set the view engine, which is used to set the templating engine used in Node.js.
一旦使用“ require”命令將模組包括在內並建立了“物件”,便可以呼叫快速模組的所需方法。在這裡,我們使用set命令設定檢視引擎,該檢視引擎用於設定Node.js中使用的模板引擎
  
Note:(Just for the reader's understanding; a templating engine is an approach for injecting values in an application by picking up data from data files. This concept is pretty famous in Angular JS wherein the curly braces {{ key }} is used to substitutes values in the web page. The word 'key' in the curly braces basically denotes the variable which will be substituted by a value when the page is displayed.)
注意:模板引擎是一種通過從資料檔案中拾取資料來在應用程式中注入值的方法。這個概念在Angular JS中非常有名,其中花括號{{key}}用於替換網頁中的值。大括號中的“鍵”一詞基本上表示在顯示頁面時將由值替換的變數。)
  
4. Here we are using the listen to method to make the application listen on a particular port number.
在這裡,我們使用listen方法來使應用程式偵聽特定的埠號

Creating NPM modules
  
Node.js has the ability to create custom modules and allows you to include those custom modules in your Node.js application.
Node.js能夠建立自定義模組,並允許您將這些自定義模組包括在Node.js應用程式中
  
Let's look at a simple example of how we can create our own module and include that module in our main application file. Our module will just do a simple task of adding two numbers.
讓我們看一個簡單的示例,說明如何建立自己的模組並將該模組包含在主應用程式檔案中。我們的模組將完成一個簡單的新增兩個數字的任務
  
Let's follow the below steps to see how we can create modules and include them in our application.
讓我們按照以下步驟檢視如何建立模組並將其包含在我們的應用程式中

Step 1) Create a file called "Addition.js" and include the below code. This file will contain the logic for your module.

Below is the code which would go into this file;

// 上圖程式碼為Node.js V8.4.0
// 以下程式碼為Node.js V12.16.3
module.exports.AddNumber = (a, b) => {
    return a + b;
};

Step 2) Create a file called "app.js," which is your main application file and add the below code

// 上圖程式碼為Node.js V8.4.0
// 以下程式碼為Node.js V12.16.3
const Addition = require('./Addition')
console.log(Addition.AddNumber(1, 2));
  1. We are using the "require" keyword to include the functionality in the Addition.js file.

  2. Since the functions in the Addition.js file are now accessible, we can now make a call to the AddNumber function. In the function, we are passing 2 numbers as parameters. We are then displaying the value in the console.

Output:

  • When you run the app.js file, you will get an output of value 3 in the console log.
  • The result is because the AddNumber function in the Addition.js file was called successfully, and the returned value of 3 was displayed in the console.

Note: - We are not using the "Node package manager" as of yet to install our Addition.js module. This is because the module is already part of our project on the local machine. The Node package manager comes in the picture when you publish a module on the internet, which we see in the subsequent topic.

Extending modules

When creating modules, it is also possible to extend or inherit one module from another.

建立模組時,還可以擴充套件或繼承另一個模組

In modern-day programming, it's quite common to build a library of common modules and then extend the functionality of these common modules if required.

在現代程式設計中,通常會先建立一個通用模組庫,然後根據需要擴充套件這些通用模組的功能

Let's look at an example of how we can extend modules in Node.js.

讓我們看一下如何在Node.js中擴充套件模組的示例

Step 1) Create the base module.

In our example, create a file called "Tutorial.js" and place the below code.

In this code, we are just creating a function which returns a string to the console. The string returned is "Guru99 Tutorial".

module.exports.tutorial = () => {
    console.log('Guru99 Tutorial');
};

Step 2) Next, we will create our extended module. Create a new file called "NodeTutorial.js" and place the below code in the file.

const Tutor = require('./Tutorial');

module.exports.NodeTutorial = () => {
    console.log('Node Tutorial');
    
    Tutor.tutorial();
};

Note, the following key points about the above code

  1. We are using the "require" function in the new module file itself. Since we are going to extend the existing module file "Tutorial.js", we need to first include it before extending it.
  2. We then create a function called "Nodetutorial." This function will do 2 things,
  • It will send a string "Node Tutorial" to the console.
  • It will send the string "Guru99 Tutorial" from the base module "Tutorial.js" to our extended module "NodeTutorial.js".

Step 3) Create your main app.js file, which is your main application file and include the below code.

const localTutor = require('./NodeTutorial');

localTutor.NodeTutorial();

Publishing NPM(Node Package Manager) Modules

One can publish their own module to their own Github repository.

By publishing your module to a central location, you are then not burdened with having to install yourself on every machine that requires it.

Instead, you can use the install command of npm and install your published npm module.

The following steps need to be followed to publish your npm module

Step 1) Create your repository on GitHub (an online code repository management tool). It can be used for hosting your code repositories.

在GitHub(線上程式碼儲存庫管理工具)上建立儲存庫。它可以用於託管您的程式碼儲存庫

Step 2) You need to tell your local npm installation on who you are. Which means that we need to tell npm who is the author of this module, what is the email id and any company URL, which is available which needs to be associated with this id. All of these details will be added to your npm module when it is published.

The below commands sets the name, email and URL of the author of the npm module.

npm set init.author.name "Unity."

npm set init.author.email "guru99@gmail.com "

npm set init.author.url http://Guru99.com

Step 3) The next step is to login into npm using the credentials provided in the last step. To login, you need to use the below command

npm login

Step 4) Initialize your package – The next step is to initialize the package to create the package.json file. This can be done by issuing the below command

npm init

When you issue the above command, you will be prompted for some questions. The most important one is the version number for your module.

Step 5) Publish to GitHub – The next step is to publish your source files to GitHub. This can be done by running the below commands.

釋出到GitHub –下一步是將原始檔釋出到GitHub。可以通過執行以下命令來完成

git add.
git commit -m "Initial release"
git tag v0.0.1 
git push origin master --tags

Step 6) Publish your module – The final bit is to publish your module into the npm registry. This is done via the below command.

釋出模組–最後一點是將模組釋出到npm登錄檔中。這是通過以下命令完成的

npm publish

Managing third party packages with npm

As we have seen, the "Node package manager" has the ability to manage modules, which are required by Node.js applications.

如我們所見,“ Node包管理器”具有管理Node.js應用程式所需的模組的能力

Let's look at some of the functions available in the node package manager for managing modules

  1. Installing packages in global mode – Modules can be installed at the global level, which just basically means that these modules would be available for all Node.js projects on a local machine. The example below shows how to install the "express module" with the global option.

    以全域性模式安裝軟體包–模組可以在全域性級別安裝,這基本上意味著這些模組可用於本地計算機上的所有Node.js專案。下面的示例顯示瞭如何使用全域性選項安裝“ express模組”。

    npm install express –global

    The global option in the above statement is what allows the modules to be installed at a global level.

    上述語句中的global選項是允許在全域性級別安裝模組的選項

  2. Listing all of the global packages installed on a local machine. This can be done by executing the below command in the command prompt

    列出安裝在本地計算機上的所有全域性軟體包。這可以通過在命令提示符下執行以下命令來完成

    npm list --global

    Below is the output which will be shown, if you have previously installed the "express module" on your system.

    如果您先前在系統上安裝了“ express模組”,則將顯示以下輸出

    Here you can see the different modules installed on the local machine.

  1. Installing a specific version of a package – Sometimes there may be a requirement to install just the specific version of a package. Once you know package name and the relevant version that needs to be installed, you can use the npm install command to install that specific version.

The example below shows how to install the module called underscore with a specific version of 1.7.0

npm install underscore@1.7.0

  1. Updating a package version – Sometimes you may have an older version of a package in a system, and you may want to update to the latest one available in the market. To do this, one can use the npm update command. The example below shows how to update the underscore package to the latest version

npm update underscore

  1. Searching for a particular package – To search whether a particular version is available on the local system or not, you can use the search command of npm. The example below will check if the express module is installed on the local machine or not.

搜尋特定的軟體包–要搜尋本地系統上是否有特定的版本,可以使用npm的search命令。下面的示例將檢查Express模組是否已安裝在本地計算機上

npm search express

  1. Uninstalling a package – The same in which you can install a package, you can also uninstall a package. The uninstallation of a package is done with the uninstallation command of npm. The example below shows how to uninstall the express module

npm uninstall express

What is the package.json file

The "package.json" file is used to hold the metadata about a particular project. This information provides the Node package manager the necessary information to understand how the project should be handled along with its dependencies.

“ package.json”檔案用於儲存有關特定專案的後設資料。此資訊為Node包管理器提供了必要的資訊,以瞭解應如何處理專案及其依賴項

The package.json files contain information such as the project description, the version of the project in a particular distribution, license information, and configuration data.

package.json檔案包含諸如專案描述,特定分發中的專案版本,許可證資訊和配置資料之類的資訊

The package.json file is normally located at the root directory of a Node.js project.

package.json檔案通常位於Node.js專案的根目錄下

Let's take an example of how the structure of a module looks when it is installed via npm.

The below snapshot shows the file contents of the express module when it is included in your Node.js project. From the snapshot, you can see the package.json file in the express folder.

If you open the package.json file, you will see a lot of information in the file.

Below is a snapshot of a portion of the file. The express@~4.13.1 mentions the version number of the express module being used.

Summary

  • A module in Node.js is a logical encapsulation of code in a single unit. Separation into modules makes code more manageable and maintainable for future purposes

    Node.js中的模組是程式碼在單個單元中的邏輯封裝。分離成模組使程式碼更易於管理和維護,以備將來使用

  • There are many modules available in the market which can be used within Node.js such as express, underscore, MongoDB, etc.

  • The node package manager (npm) is used to download and install modules which can then be used in a Node.js application.

  • One can create custom NPM modules, extend these modules, and also publish these modules.

    可以建立自定義NPM模組,擴充套件這些模組,也可以釋出這些模組

  • The Node package manager has a complete set of commands to manage the npm modules on the local system such as the installation, un-installation, searching, etc.

  • The package.json file is used to hold the entire metadata information for an npm module.

相關文章