将 fs.writeFile() 与文件描述符一起使用
当 file
是文件描述符时,其行为几乎与直接调用 fs.write()
相同,例如:
fs.write(fd, Buffer.from(data, options.encoding), callback);
其含义是常见的混淆来源。 在文件描述符的情况下,文件不会被替换! 数据不一定写入文件的开头,文件的原始数据可以保留在新写入的数据之前和/或之后。
例如,如果连续调用 fs.writeFile()
两次,首先写入字符串 'Hello'
,然后写入字符串 ', World'
,该文件将包含 'Hello, World'
,并且可能包含文件的一些原始数据(这取决于原始文件的大小和文件描述符的位置)。
如果使用文件名而不是描述符,则文件将保证仅包含 ', World'
。
When file
is a file descriptor, the behavior is almost identical to directly
calling fs.write()
like:
fs.write(fd, Buffer.from(data, options.encoding), callback);
The difference from directly calling fs.write()
is that under some unusual
conditions, fs.write()
may write only part of the buffer and will need to be
retried to write the remaining data, whereas fs.writeFile()
will retry 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.
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'
.