fs.write(fd, buffer[, offset[, length[, position]]], callback)


buffer 写入到 fd 指定的文件。

offset 决定 buffer 中要被写入的部位, length 是一个整数,指定要写入的字节数。

position 指定文件开头的偏移量(数据应该被写入的位置)。 如果 typeof position !== 'number',则数据会被写入当前的位置。 参阅 pwrite(2)

回调有三个参数 (err, bytesWritten, buffer),其中 bytesWritten 指定 buffer 中被写入的字节数。

如果调用此方法的 util.promisify() 版本,则返回的 Promise 会返回具有 bytesWrittenbuffer 属性的 Object

在同一个文件上多次使用 fs.write() 且不等待回调是不安全的。 对于这种情况,建议使用 fs.createWriteStream()

在 Linux 上,当以追加模式打开文件时,写入无法指定位置。 内核会忽略位置参数,并始终将数据追加到文件的末尾。

Write buffer to the file specified by fd.

offset determines the part of the buffer to be written, and length is an integer specifying the number of bytes to write.

position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position. See pwrite(2).

The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.

If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with bytesWritten and buffer properties.

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.

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.