fs.read(fd, buffer, offset, length, position, callback)
fd<integer>buffer<Buffer> | <TypedArray> | <DataView> 数据将要写入的缓冲区。offset<integer> 写入数据到buffer的位置。length<integer> 要读取的字节数。position<integer> | <bigint> | <null> 指定从文件的哪个位置开始读取。如果position为null或-1,数据将从当前文件位置开始读取,并且文件位置会被更新。如果position是一个整数,文件位置将保持不变。callback<Function>
从由 fd 指定的文件中读取数据。
【Read data from the file specified by fd.】
回调函数会接收三个参数,(err, bytesRead, buffer)。
【The callback is given the three arguments, (err, bytesRead, buffer).】
如果文件没有被同时修改,当读取的字节数为零时,就到达了文件末尾。
【If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.】
如果以其 util.promisify()ed 版本调用此方法,它会返回一个包含 bytesRead 和 buffer 属性的 Object 的 Promise。
【If this method is invoked as its util.promisify()ed version, it returns
a promise for an Object with bytesRead and buffer properties.】
fs.read() 方法从指定的文件描述符(fd)对应的文件中读取数据。length 参数表示 Node.js 将尝试从内核读取的最大字节数。然而,实际读取的字节数(bytesRead)可能由于各种原因低于指定的 length。
【The fs.read() method reads data from the file specified
by the file descriptor (fd).
The length argument indicates the maximum number
of bytes that Node.js
will attempt to read from the kernel.
However, the actual number of bytes read (bytesRead) can be lower
than the specified length for various reasons.】
例如:
【For example:】
- 如果文件小于指定的
length,bytesRead将设置为实际读取的字节数。 - 如果文件在缓冲区填满之前遇到 EOF(文件结束),Node.js 会读取所有可用的字节直到遇到 EOF,并且回调中的
bytesRead参数会指示实际读取的字节数,这可能少于指定的length。 - 如果文件位于慢速网络
filesystem上或在读取过程中遇到其他问题,bytesRead可能会小于指定的length。
因此,在使用 fs.read() 时,检查 bytesRead 的值以确定实际从文件中读取了多少字节非常重要。根据你的应用逻辑,你可能需要处理 bytesRead 小于指定 length 的情况,例如,如果你需要读取最少字节,可以将读取调用放在循环中。
【Therefore, when using fs.read(), it's important to
check the bytesRead value to
determine how many bytes were actually read from the file.
Depending on your application
logic, you may need to handle cases where bytesRead
is lower than the specified length,
such as by wrapping the read call in a loop if you require
a minimum amount of bytes.】
这种行为类似于 POSIX 的 preadv2 函数。
【This behavior is similar to the POSIX preadv2 function.】