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 8675 (
length 8366) of buffer to the file referenced by file descriptor fd, insertion beginning at position 100:
var buffer = new Buffer(8675);
fs.open("index.html", "w", function(err, fd) {
fs.write(fd, buffer, 309, 8366, 100, function(err, writtenBytes, buffer) {
console.log("Wrote " + writtenBytes + " bytes to file");
// Wrote 8366 bytes to file
});
});Note
Note that for files opened in append (a) mode some operating systems may ignore...