Node.js 模块
在 Node.js 中,模块是封装的代码块,它们根据其相关功能与外部应用程序进行通信。模块可以是单个文件或多个文件/文件夹的集合。程序员严重依赖模块的原因是它们的可重用性以及将复杂代码分解为可管理块的能力。
模块分为三种类型:
- 核心模块
- 本地模块
- 第三方模块
核心模块: Node.js 有许多内置模块,这些模块是平台的一部分,并且随 Node.js 安装一起提供。可以使用require函数将这些模块加载到程序中。
句法:
var module = require('module_name');
require()函数将根据特定模块返回的内容返回一个 JavaScript 类型。以下示例演示如何使用 Node.js Http 模块创建 Web 服务器。
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to this page!');
res.end();
}).listen(3000);
在上面的示例中, require()函数返回一个对象,因为 Http 模块将其功能作为对象返回。当有人试图通过 3000 端口访问计算机时,将执行函数http.createServer() 方法。 res.writeHead() 方法是状态码,其中 200 表示正常,而第二个参数是包含响应的对象标题。
以下列表包含 Node.js 中的一些重要核心模块:
Core Modules | Description |
---|---|
http | creates an HTTP server in Node.js. |
assert | set of assertion functions useful for testing. |
fs | used to handle file system. |
path | includes methods to deal with file paths. |
process | provides information and control about the current Node.js process. |
os | provides information about the operating system. |
querystring | utility used for parsing and formatting URL query strings. |
url | module provides utilities for URL resolution and parsing. |
本地模块:与内置模块和外部模块不同,本地模块是在 Node.js 应用程序中本地创建的。让我们创建一个简单的计算模块来计算各种操作。创建一个包含以下代码的 calc.js 文件:
文件名:calc.js
exports.add = function (x, y) {
return x + y;
};
exports.sub = function (x, y) {
return x - y;
};
exports.mult = function (x, y) {
return x * y;
};
exports.div = function (x, y) {
return x / y;
};
由于此文件通过导出向外部世界提供属性,因此另一个文件可以使用 require()函数使用其导出的功能。
文件名:index.js
var calculator = require('./calc');
var x = 50, y = 10;
console.log("Addition of 50 and 10 is "
+ calculator.add(x, y));
console.log("Subtraction of 50 and 10 is "
+ calculator.sub(x, y));
console.log("Multiplication of 50 and 10 is "
+ calculator.mult(x, y));
console.log("Division of 50 and 10 is "
+ calculator.div(x, y));
运行此程序的步骤:使用以下命令运行index.js文件:
node index.js
输出:
Addition of 50 and 10 is 60
Subtraction of 50 and 10 is 40
Multiplication of 50 and 10 is 500
Division of 50 and 10 is 5
注意:此模块还隐藏了模块外部不需要的功能。
第三方模块:第三方模块是使用 Node Package Manager (NPM) 在线提供的模块。这些模块可以安装在项目文件夹中或全局安装。一些流行的第三方模块是 mongoose、express、angular 和 react。
例子:
- npm 安装快递
- npm 安装猫鼬
- npm install -g @angular/cli