使用 fs.writeFile() 与文件描述符
【Using fs.writeFile() with file descriptors】
当 file 是一个文件描述符时,其行为几乎与直接调用 fs.write() 相同,如下所示:
【When file is a file descriptor, the behavior is almost identical to directly
calling fs.write() like:】
import { write } from 'node:fs';
import { Buffer } from 'node:buffer';
write(fd, Buffer.from(data, options.encoding), callback); 与直接调用 fs.write() 的区别在于,在某些异常情况下,fs.write() 可能只写入缓冲区的一部分,需要重试才能写入剩余的数据,而 fs.writeFile() 会重试直到数据完全写入(或发生错误)。
【The difference from directly calling fs.write() is that under some unusual
conditions, fs.write() might write only part of the buffer and need to be
retried to write the remaining data, whereas fs.writeFile() retries until
the data is entirely written (or an error occurs).】
这所带来的影响常常是混淆的来源。在文件描述符的情况下,文件并没有被替换!数据不一定会写入文件的开头,文件的原始数据可能在新写入的数据之前和/或之后保留。
【The implications of this are a common source of confusion. In the file descriptor case, the file is not replaced! The data is not necessarily written to the beginning of the file, and the file's original data may remain before and/or after the newly written data.】
例如,如果 fs.writeFile() 连续调用两次,第一次写入字符串 'Hello',然后写入字符串 ', World',文件将包含 'Hello, World',并且可能包含一些文件原有的数据(取决于原始文件的大小以及文件描述符的位置)。如果使用文件名而不是描述符,文件将保证只包含 ', World'。
【For example, if fs.writeFile() is called twice in a row, first to write the
string 'Hello', then to write the string ', World', the file would contain
'Hello, World', and might contain some of the file's original data (depending
on the size of the original file, and the position of the file descriptor). If
a file name had been used instead of a descriptor, the file would be guaranteed
to contain only ', World'.】