使用 Node.js 中的文件描述符
¥Working with file descriptors in Node.js
在能够与文件系统中的文件交互之前,你必须获取文件描述符。
¥Before you're able to interact with a file that sits in your filesystem, you must get a file descriptor.
文件描述符是对打开文件的引用,是使用 fs
模块提供的 open()
方法打开文件返回的数字 (fd)。这个数字 (fd
) 唯一地标识操作系统中打开的文件:
¥A file descriptor is a reference to an open file, a number (fd) returned by opening the file using the open()
method offered by the fs
module. This number (fd
) uniquely identifies an open file in operating system:
const fs = require('node:fs');
fs.open('/Users/joe/test.txt', 'r', (err, fd) => {
// fd is our file descriptor
});
注意我们用作 fs.open()
调用的第二个参数的 r
。
¥Notice the r
we used as the second parameter to the fs.open()
call.
该标志表示我们打开文件进行读取。
¥That flag means we open the file for reading.
你常用的其他标志是:
¥Other flags you'll commonly use are:
标志 | 描述 | 如果文件不存在,则会创建它 |
---|---|---|
r+ | 此标志打开文件进行读写 | ❌ |
w+ | 此标志打开文件进行读写,并将流定位在文件开头 | ✅ |
a | 此标志打开文件进行写入,并将流定位在文件末尾 | ✅ |
a+ | 此标志打开文件进行读写,并将流定位在文件末尾 | ✅ |
你也可以使用 fs.openSync
方法打开文件,该方法返回文件描述符,而不是在回调中提供它:
¥You can also open the file by using the fs.openSync
method, which returns the file descriptor, instead of providing it in a callback:
const fs = require('node:fs');
try {
const fd = fs.openSync('/Users/joe/test.txt', 'r');
} catch (err) {
console.error(err);
}
一旦你获得文件描述符,无论你选择哪种方式,你都可以执行所有需要它的操作,例如调用 fs.close()
和许多其他与文件系统交互的操作。
¥Once you get the file descriptor, in whatever way you choose, you can perform all the operations that require it, like calling fs.close()
and many other operations that interact with the filesystem.
你也可以使用 fs/promises
模块提供的基于 promise 的 fsPromises.open
方法打开文件。
¥You can also open the file by using the promise-based fsPromises.open
method offered by the fs/promises
module.
fs/promises
模块仅从 Node.js v14 开始可用。在 v14 之前、v10 之后,你可以改用 require('fs').promises
。在 v10 之前、v8 之后,你可以使用 util.promisify
将 fs
方法转换为基于 promise 的方法。
¥The fs/promises
module is available starting only from Node.js v14. Before v14, after v10, you can use require('fs').promises
instead. Before v10, after v8, you can use util.promisify
to convert fs
methods into promise-based methods.
const fs = require('node:fs/promises');
// Or const fs = require('fs').promises before v14.
async function example() {
let filehandle;
try {
filehandle = await fs.open('/Users/joe/test.txt', 'r');
console.log(filehandle.fd);
console.log(await filehandle.readFile({ encoding: 'utf8' }));
} finally {
if (filehandle) await filehandle.close();
}
}
example();
以下是 util.promisify
的示例:
¥Here is an example of util.promisify
:
const fs = require('node:fs');
const util = require('node:util');
async function example() {
const open = util.promisify(fs.open);
const fd = await open('/Users/joe/test.txt', 'r');
}
example();
要查看有关 fs/promises
模块的更多详细信息,请查看 fs/promises API。
¥To see more details about the fs/promises
module, please check fs/promises API.