Appearance
第3章:Node.js 全局对象与核心模块
3.1 全局对象
Node.js 中有一些全局对象,它们在任何模块中都可以直接使用,不需要通过 require() 引入。
global 对象
global 是 Node.js 中的全局对象,类似于浏览器中的 window 对象。所有全局变量和函数都挂载在 global 对象上。
javascript
// 定义全局变量
global.myVariable = 'Hello, global!';
// 在其他模块中访问
console.log(global.myVariable); // 输出: Hello, global!console 对象
console 对象用于在控制台输出信息,常用方法:
console.log():输出普通信息console.error():输出错误信息console.warn():输出警告信息console.info():输出信息性内容console.table():以表格形式输出对象console.time():开始计时console.timeEnd():结束计时并输出时间
javascript
// 使用 console 对象
console.log('普通信息');
console.error('错误信息');
console.warn('警告信息');
console.info('信息性内容');
// 以表格形式输出对象
const users = [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 }
];
console.table(users);
// 计时
console.time('执行时间');
// 执行一些操作
for (let i = 0; i < 1000000; i++) {
// 空操作
}
console.timeEnd('执行时间');process 对象
process 对象表示当前 Node.js 进程,提供了许多与进程相关的属性和方法。
常用属性和方法:
process.env:环境变量process.argv:命令行参数process.cwd():当前工作目录process.exit():退出进程process.version:Node.js 版本
javascript
// 使用 process 对象
console.log('环境变量:', process.env.NODE_ENV);
console.log('命令行参数:', process.argv);
console.log('当前工作目录:', process.cwd());
console.log('Node.js 版本:', process.version);
// 退出进程
// process.exit(0); // 0 表示正常退出3.2 核心模块介绍
Node.js 提供了许多核心模块,这些模块不需要安装,直接通过 require() 引入使用。
常用核心模块:
fs:文件系统操作path:路径处理url:URL 解析与处理http:创建 HTTP 服务器https:创建 HTTPS 服务器os:操作系统相关信息util:工具函数events:事件处理stream:流处理
3.3 常用核心模块实操
fs 模块:文件系统操作
fs 模块用于文件系统操作,如读取、写入、删除文件和文件夹。
异步文件读取:
javascript
const fs = require('fs');
// 异步读取文件
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('读取文件失败:', err);
return;
}
console.log('文件内容:', data);
});异步文件写入:
javascript
const fs = require('fs');
// 异步写入文件
const content = 'Hello, Node.js!';
fs.writeFile('example.txt', content, (err) => {
if (err) {
console.error('写入文件失败:', err);
return;
}
console.log('文件写入成功');
});异步删除文件:
javascript
const fs = require('fs');
// 异步删除文件
fs.unlink('example.txt', (err) => {
if (err) {
console.error('删除文件失败:', err);
return;
}
console.log('文件删除成功');
});path 模块:路径处理
path 模块用于处理文件路径,提供了许多路径操作方法。
javascript
const path = require('path');
// 路径拼接
const fullPath = path.join(__dirname, 'example.txt');
console.log('完整路径:', fullPath);
// 解析路径
const parsedPath = path.parse(fullPath);
console.log('解析路径:', parsedPath);
// 获取文件扩展名
const extname = path.extname(fullPath);
console.log('文件扩展名:', extname);
// 获取文件名
const basename = path.basename(fullPath);
console.log('文件名:', basename);
// 获取目录名
const dirname = path.dirname(fullPath);
console.log('目录名:', dirname);url 模块:URL解析与处理
url 模块用于解析和处理 URL。
javascript
const url = require('url');
const urlString = 'https://example.com:8080/path?name=John&age=20';
// 解析 URL
const parsedUrl = url.parse(urlString, true);
console.log('解析后的URL:', parsedUrl);
// 获取查询参数
console.log('查询参数:', parsedUrl.query);
console.log('name:', parsedUrl.query.name);
console.log('age:', parsedUrl.query.age);http 模块:创建简单HTTP服务器
http 模块用于创建 HTTP 服务器,是 Node.js 后端开发的核心。
javascript
const http = require('http');
// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/plain' });
// 发送响应内容
res.end('Hello, Node.js HTTP Server!\n');
});
// 监听端口
const port = 3000;
server.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});3.4 模块引入与使用语法
require() 引入模块
在 Node.js 中,使用 require() 函数引入模块:
javascript
// 引入核心模块
const fs = require('fs');
const http = require('http');
// 引入自定义模块
const myModule = require('./myModule');
// 引入第三方模块
const lodash = require('lodash');module.exports 导出模块
在 Node.js 中,使用 module.exports 导出模块:
javascript
// myModule.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
// 导出单个函数
// module.exports = add;
// 导出多个函数
module.exports = {
add,
subtract
};3.5 实操案例
案例1:读取本地文件
javascript
const fs = require('fs');
const path = require('path');
// 读取文件
const filePath = path.join(__dirname, 'data.txt');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('读取文件失败:', err);
return;
}
console.log('文件内容:');
console.log(data);
});案例2:创建简单服务器
javascript
const http = require('http');
const fs = require('fs');
const path = require('path');
// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
// 处理根路径
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js Server!\n');
}
// 处理 /about 路径
else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Page\n');
}
// 处理 404
else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found\n');
}
});
// 监听端口
const port = 3000;
server.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});小结
- Node.js 有几个重要的全局对象:global、console、process
- Node.js 提供了许多核心模块,如 fs、path、url、http 等
- 使用 require() 引入模块,使用 module.exports 导出模块
- fs 模块用于文件系统操作,支持异步和同步操作
- path 模块用于处理文件路径
- url 模块用于解析和处理 URL
- http 模块用于创建 HTTP 服务器
现在,你已经了解了 Node.js 的全局对象和核心模块,接下来让我们学习 Node.js 的模块化开发。
