Appending to a File in Node: Easy and Efficient Methods
When working with log files or any other scenario where data must be continuously added to an existing file, it's essential to know how to append without overwriting. Here's how you can achieve that in Node.js.
Initial Problem:
Attempting to write to a file using fs.writeFile() overwrites the existing content, making it unsuitable for appending.
appendFile: The Brute Force Approach
For infrequent appending, you can utilize appendFile, which opens a new file handle each time:
const fs = require('fs'); fs.appendFile('message.txt', 'data to append', function (err) { if (err) throw err; console.log('Saved!'); });
File Handle Management for Optimal Performance
For repeated appends to the same file, it's more efficient to reuse the file handle. Here's how to do it:
const fs = require('fs'); const fd = fs.openSync('message.txt', 'a');
Use fs.write() to append data to the file.
fs.write(fd, 'data to append', null, 'utf8', function(err, written, buffer) {});
fs.closeSync(fd);
This method is significantly faster than opening and closing the file handle repeatedly, especially for large files or frequent appends.
The above is the detailed content of How to Efficiently Append Data to a File in Node.js?. For more information, please follow other related articles on the PHP Chinese website!