第四章:模块系统
简要说明
Node.js 的模块系统是其核心功能之一,它允许开发者将代码分割成可重用的模块。通过模块系统,开发者可以轻松导入和使用内置模块(如 fs
、http
)以及第三方模块。Node.js 的模块系统基于 CommonJS 规范,使用 require
和 module.exports
来实现模块的导入和导出。
关键知识点
1. CommonJS 模块规范
CommonJS 是 Node.js 采用的模块规范,它定义了模块的导入和导出方式。每个文件在 Node.js 中都被视为一个独立的模块,模块内部的变量、函数和对象默认是私有的,只有通过 module.exports
导出的内容才能被其他模块访问。
2. require
和 module.exports
require
require
是 Node.js 中用于导入模块的函数。它可以导入内置模块、第三方模块以及自定义模块。
// 导入内置模块
const fs = require('fs');
// 导入第三方模块
const express = require('express');
// 导入自定义模块
const myModule = require('./myModule');
module.exports
module.exports
是 Node.js 中用于导出模块内容的对象。通过 module.exports
,可以将模块中的函数、对象或变量暴露给其他模块使用。
// myModule.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
// 在另一个文件中使用
const greet = require('./myModule');
console.log(greet('World')); // 输出: Hello, World!
3. 内置模块的使用
Node.js 提供了许多内置模块,这些模块可以直接通过 require
导入并使用。以下是两个常用的内置模块示例:
fs
模块
fs
模块用于文件系统操作,如读取文件、写 入文件等。
const fs = require('fs');
// 读取文件
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 写入文件
fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully');
});
http
模块
http
模块用于创建 HTTP 服务器和客户端。
const http = require('http');
// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
// 监听端口
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
总结
Node.js 的模块系统是构建复杂应用的基础。通过 require
和 module.exports
,开发者可以轻松地组织和重用代码。内置模块如 fs
和 http
提供了强大的功能,使得 Node.js 能够处理文件操作、网络请求等任务。掌握模块系统是学习 Node.js 的关键一步,为后续章节的学习打下坚实的基础。
下一章预告:第五章将介绍 Node.js 中的异步编程,包括回调函数、Promise 和 async/await 的使用。