fs.write(fd, string[, position[, encoding]], callback)
fd<integer>string<string>position<integer> | <null> 默认值:nullencoding<string> 默认值:'utf8'callback<Function>
将 string 写入由 fd 指定的文件。如果 string 不是字符串,将抛出异常。
【Write string to the file specified by fd. If string is not a string,
an exception is thrown.】
position 指的是应将此数据写入文件起始位置的偏移量。如果 typeof position !== 'number',数据将写入当前位置。参见 pwrite(2)。
encoding 是预期的字符串编码。
回调函数将接收参数 (err, written, string),其中 written 指定传入字符串所需写入的 字节 数。写入的字节数不一定与写入的字符串字符数相同。参见 Buffer.byteLength。
【The callback will receive the arguments (err, written, string) where written
specifies how many bytes the passed string required to be written. Bytes
written is not necessarily the same as string characters written. See
Buffer.byteLength.】
在同一个文件上多次使用 fs.write() 而不等待回调是不安全的。对于这种情况,建议使用 fs.createWriteStream()。
【It is unsafe to use fs.write() multiple times on the same file without waiting
for the callback. For this scenario, fs.createWriteStream() is
recommended.】
在 Linux 上,当文件以追加模式打开时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。
【On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.】
在 Windows 上,如果文件描述符连接到控制台(例如 fd == 1 或 stdout),默认情况下包含非 ASCII 字符的字符串将无法正确显示,无论使用何种编码。可以通过使用 chcp 65001 命令更改活动代码页来配置控制台以正确显示 UTF-8。有关更多详细信息,请参阅 chcp 文档。
【On Windows, if the file descriptor is connected to the console (e.g. fd == 1
or stdout) a string containing non-ASCII characters will not be rendered
properly by default, regardless of the encoding used.
It is possible to configure the console to render UTF-8 properly by changing the
active codepage with the chcp 65001 command. See the chcp docs for more
details.】