文件描述符
【File descriptors】
在 POSIX 系统中,对于每个进程,内核都会维护一个当前打开文件和资源的表。每个打开的文件都会分配一个简单的数字标识符,称为 文件描述符。在系统级别上,所有文件系统操作都使用这些文件描述符来识别和跟踪每个特定文件。Windows 系统使用一种不同但概念上类似的机制来跟踪资源。为了简化用户的操作,Node.js 把操作系统之间的差异抽象掉,并为所有打开的文件分配一个数字文件描述符。
【On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a file descriptor. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the differences between operating systems and assigns all open files a numeric file descriptor.】
基于回调的 fs.open() 方法和同步的 fs.openSync() 方法用于打开文件并分配一个新的文件描述符。一旦分配,文件描述符可以用于读取文件数据、写入文件数据或请求文件相关信息。
【The callback-based fs.open(), and synchronous fs.openSync() methods open a
file and allocate a new file descriptor. Once allocated, the file descriptor may
be used to read data from, write data to, or request information about the file.】
操作系统会限制在任意给定时间内可以打开的文件描述符数量,因此在操作完成后关闭描述符是至关重要的。如果不这样做,将导致内存泄漏,最终可能导致应用崩溃。
【Operating systems limit the number of file descriptors that may be open at any given time so it is critical to close the descriptor when operations are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash.】
import { open, close, fstat } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('/open/some/file.txt', 'r', (err, fd) => {
if (err) throw err;
try {
fstat(fd, (err, stat) => {
if (err) {
closeFd(fd);
throw err;
}
// use stat
closeFd(fd);
});
} catch (err) {
closeFd(fd);
throw err;
}
}); 基于 Promise 的 API 使用 <FileHandle> 对象来代替数字文件描述符。这些对象由系统更好地管理,以确保资源不会泄漏。然而,在操作完成后仍然需要关闭它们:
【The promise-based APIs use a <FileHandle> object in place of the numeric file descriptor. These objects are better managed by the system to ensure that resources are not leaked. However, it is still required that they are closed when operations are completed:】
import { open } from 'node:fs/promises';
let file;
try {
file = await open('/open/some/file.txt', 'r');
const stat = await file.stat();
// use stat
} finally {
await file.close();
}