Node.js 模块详解

模块的概念

Node.js 运行在 V8 JavaScript 引擎上,通过 require() 函数导入相关模块来处理服务器端的各种进程。一个 Node.js 模块可以是一个函数库、类集合或其他可重用的代码,通常存储在一个或多个 .js 文件中。

例如,启动一个 Node.js 服务器时,我们需要导入 http 模块:

javascript 复制代码
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

模块的类型

Node.js 中的模块主要分为三种类型:

第三方模块

这些模块由独立开发者开发,并在 NPM 仓库中提供使用。要在项目中使用这些模块,需要先在全局或项目文件夹中安装它们。

例如,安装 Express 模块:

bash 复制代码
npm install express

使用 Express 模块:

javascript 复制代码
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Example app listening on port 3000!');
});

内置模块

Node.js 运行时软件自带了一些核心模块,如 httpfsconsole 等。这些模块无需安装,但使用时仍需要通过 require() 函数导入(除了少数全局对象如 processbufferconsole)。

例如,使用 fs 模块读取文件:

javascript 复制代码
const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

本地模块

本地模块是你自己创建的 .js 文件,其中包含了你的应用程序所需的函数或类的定义。这些模块位于你的 Node.js 应用程序文件夹中,同样需要通过 require() 函数导入。

每个 .js 文件都有一个特殊的 module 对象,其 exports 属性用于向外部代码暴露特定的函数、对象或变量。

例如,创建一个名为 functions.js 的本地模块:

javascript 复制代码
// functions.js
exports.power = (x, y) => Math.pow(x, y);
exports.squareRoot = x => Math.sqrt(x);
exports.log = x => Math.log(x);

在主应用程序中使用这个本地模块:

javascript 复制代码
const mathFunctions = require('./functions');

console.log(mathFunctions.power(2, 3));  // 输出: 8
console.log(mathFunctions.squareRoot(16));  // 输出: 4
console.log(mathFunctions.log(10));  // 输出: 2.302585092994046

通过使用模块,我们可以将 Node.js 应用程序的功能分割成更小、更易管理的部分,提高代码的可读性和可维护性。

相关推荐
Revolution614 小时前
Node.js 是什么:前端项目里哪些事情由它完成
前端·面试·node.js
Revolution614 小时前
Nest.js 是什么:怎样用它写出第一个后端接口
后端·node.js·nestjs
柳林林6 小时前
解决 nvm 切换 Node.js 版本时报“没有文件扩展 ‘.vbs’ 的脚本引擎”错误
node.js
To_OC15 小时前
从 0 到 1:Milvus + 大模型打造私人记忆知识库
人工智能·node.js·llm
孟陬1 天前
介绍 Node.js v22 新增的 `toArray` 方法
node.js·deno·bun
卡兹墨1 天前
针对高并发、数据量大的场景,通常会考虑采用分库分表进行优化。在这篇文章,我们重点盘点一下Node.js主流ORM框架的动态分表方案 ...
node.js
行走的陀螺仪2 天前
一次 opencode + OpenPencil MCP 协同解析 .fig 文件的踩坑实录
node.js·figma·mcp·opencode
JasonMa1532 天前
从零搭建一个微信小程序活动管理平台(一):架构设计与技术选型
javascript·微信小程序·node.js
濮水大叔2 天前
NestJS 与 CabloyJS 的 env/config 架构对比:从环境变量到实例级配置
前端·node.js·nestjs
TDengine (老段)2 天前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine