1. fs
模块
用于与文件系统进行交互,支持文件的读取、写入、删除等操作。它是进行文件操作最常用的模块。
常用方法:
fs.readFile(path, encoding, callback)
: 异步读取文件。
fs.writeFile(path, data, encoding, callback)
: 异步写入数据到文件。
fs.appendFile(path, data, encoding, callback)
: 异步追加数据到文件。
fs.mkdir(path, callback)
: 创建目录。
fs.readdir(path, callback)
: 读取目录内容。
最常用的就是readFile和writeFile代码示例如下
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
2. http
模块
用于创建 HTTP 服务器,处理 HTTP 请求和响应。
常用方法:
http.createServer([options], requestListener)
: 创建一个 HTTP 服务器。
http.get(url, [options], callback)
: 发送 HTTP GET 请求。
http.request(options, callback)
: 发起 HTTP 请求,允许更多自定义设置。
我们可以利用它创造应该web服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(8080, () => {
console.log('Server is running at http://localhost:8080/');
});
3. url
模块
用于解析和处理 URL 地址。
常用方法:
url.parse(urlString, [parseQueryString], [slashesDenoteHost])
: 解析一个 URL 字符串。
url.format(urlObject)
: 将 URL 对象格式化为字符串。
url.resolve(from, to)
: 解析两个路径,返回相对路径。
const url = require('url');
const myUrl = url.parse('https://www.example.com:8080/path?name=example#hash');
console.log(myUrl.hostname); // 'www.example.com'
5.events
模块
提供事件驱动的编程模型,允许你创建和处理事件
常用方法:
EventEmitter.emit(eventName, [...args])
: 触发指定事件。
EventEmitter.on(eventName, listener)
: 为事件添加监听器。
EventEmitter.once(eventName, listener)
: 为事件添加一次性监听器。
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('greet', () => {
console.log('Hello, world!');
});
eventEmitter.emit('greet'); // 输出 'Hello, world!'