Writing to a file
As with reading files, Node provides a rich collection of tools for writing to files. We'll see how Node makes it as easy to target a file's contents byte-by-byte, as it is to pipe continuous streams of data into a single writable file.
Writing byte by byte
The fs.write method is the most low-level way Node offers for writing files. This method gives us precise control over where bytes will be written to in a file.
fs.write(fd, buffer, offset, length, position, callback)
To write the collection of bytes between positions 309 and 8,675 (length 8,366) of buffer to the file referenced by file descriptor fd, insertion beginning at position 100:
let buffer = Buffer.alloc(8675);
fs.open("index.html", "w", (err, fd) => {
fs.write(fd, buffer, 309, 8366, 100, (err, writtenBytes, buffer) => {
console.log(`Wrote ${writtenBytes} bytes to file`);
// Wrote 8366 bytes to file
});
}); Note
Note that for files opened in the append (a) mode, some operating systems may ignore...