filehandle.write(string[, position[, encoding]])


  • string <string>

  • position <integer> | <null> 要写入来自 string 的数据的文件的开头偏移量。如果 position 不是 number,则数据将写入当前位置。有关更多详细信息,请参阅 POSIX pwrite(2) 文档。默认值:null

    ¥position <integer> | <null> The offset from the beginning of the file where the data from string should be written. If position is not a number the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail. Default: null

  • encoding <string> 预期的字符串编码。默认值:'utf8'

    ¥encoding <string> The expected string encoding. Default: 'utf8'

  • 返回:<Promise>

    ¥Returns: <Promise>

string 写入文件。如果 string 不是字符串,则 promise 使用错误拒绝。

¥Write string to the file. If string is not a string, the promise is rejected with an error.

这个 promise 是通过一个包含两个属性的对象来实现的:

¥The promise is fulfilled with an object containing two properties:

  • bytesWritten <integer> 写入的字节数

    ¥bytesWritten <integer> the number of bytes written

  • buffer <string> 对被写入的 string 的引用。

    ¥buffer <string> a reference to the string written.

在同一个文件上多次使用 filehandle.write() 而不等待 promise 被履行(或拒绝)是不安全的。对于这种情况,请使用 filehandle.createWriteStream()

¥It is unsafe to use filehandle.write() multiple times on the same file without waiting for the promise to be fulfilled (or rejected). For this scenario, use filehandle.createWriteStream().

在 Linux 上,以追加模式打开文件时,位置写入不起作用。内核会忽略位置参数,并始终将数据追加到文件末尾。

¥On Linux, positional writes do not 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.