Appearance
核心模块
Node.js 提供了一系列核心模块,这些模块是其功能的基础。以下是一些最常用的核心模块:fs、http、os 和 path 。
fs 模块 (文件系统)
fs 模块提供了丰富的 API,用于与文件系统进行交互。它支持同步和异步两种方式的文件操作 。
常用 API
fs.readFile(path[, options], callback): 异步读取文件内容。fs.writeFile(file, data[, options], callback): 异步写入文件内容。fs.stat(path, callback): 获取文件状态信息,例如判断是文件还是目录 。fs.mkdir(path[, options], callback): 创建目录。fs.rename(oldPath, newPath, callback): 重命名或移动文件 。
示例
javascript
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});http 模块
http 模块用于创建 HTTP 服务器和客户端,是构建 Web 应用的基础。
常用 API
http.createServer([options][, requestListener]): 创建一个 HTTP 服务器实例。server.listen(port[, host][, backlog][, callback]): 启动服务器并监听指定端口。http.request(options[, callback]): 发起 HTTP 请求。
示例
javascript
const http = require('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/');
});os 模块
os 模块提供了与操作系统相关的实用方法和属性。
常用 API
os.platform(): 返回操作系统平台,如 'darwin', 'win32'。os.cpus(): 返回一个对象数组,包含每个 CPU/core 的信息。os.homedir(): 返回当前用户的主目录路径。os.tmpdir(): 返回操作系统的默认临时文件目录 。
示例
javascript
const os = require('os');
console.log('Platform:', os.platform());
console.log('Home Directory:', os.homedir());path 模块
path 模块用于处理和转换文件路径,确保跨操作系统的兼容性。
常用 API
path.join([...paths]): 将多个路径片段连接成一个规范化的路径。path.resolve([...paths]): 将路径或路径片段的序列解析为绝对路径。path.basename(path[, ext]): 返回路径的最后一部分。path.dirname(path): 返回路径的目录名。path.extname(path): 返回路径的扩展名。
示例
javascript
const path = require('path');
const myPath = path.join('/users', 'test', 'file.txt');
console.log(myPath); // 输出: /users/test/file.txt (在 POSIX 系统上)
const resolvedPath = path.resolve('file.txt');
console.log(resolvedPath); // 输出当前工作目录下的绝对路径