Reading and Writing with File Descriptors
What You'll Learn
You'll learn how to use fs.read() and fs.write() to perform precise, byte-level manipulation of files using file descriptors.
Beyond Simple File Operations
Previously, you used fs.readFile() and fs.writeFile() to work with entire files at once. But what if you need to read just 100 bytes from the middle of a large file, or write data at a specific position without overwriting everything else? That's where fs.read() and fs.write() come in.
Think of it like streaming video: instead of downloading the entire movie before watching, you grab just the chunk you need right now.
Using fs.read() for Precise Reading
Once you have a file descriptor from fs.open(), you can read specific portions:
const fs = require('fs');
fs.open('data.txt', 'r', (err, fd) => {
if (err) throw err;
const buffer = Buffer.alloc(10); // Space for 10 bytes
fs.read(fd, buffer, 0, 10, 5, (err, bytesRead, buffer) => {
// fd: file descriptor
// buffer: where to store data
// 0: start at buffer position 0
// 10: read 10 bytes
// 5: start reading from file position 5
console.log(`Read ${bytesRead} bytes:`, buffer.toString());
fs.close(fd, () => {});
});
});
Using fs.write() for Precise Writing
Similarly, fs.write() lets you write data at exact positions:
const content = Buffer.from('Hello');
fs.open('output.txt', 'r+', (err, fd) => {
if (err) throw err;
fs.write(fd, content, 0, 5, 10, (err, bytesWritten) => {
// Write 5 bytes from content starting at file position 10
console.log(`Wrote ${bytesWritten} bytes`);
fs.close(fd, () => {});
});
});
Key Takeaway: fs.read() and fs.write() give you surgical control over file I/O, letting you read or write specific byte ranges at exact positions using file descriptors.