Home >Web Front-end >JS Tutorial >How to Efficiently Append Data to Files in Node.js?
Appending to Files in Node.js
When attempting to append a string to a log file, using writeFile may result in erasing the existing content. To address this issue, Node.js provides alternative methods for appending data to files.
Easy Method: AppendFile
For occasional appends, appendFile can be employed. It creates a new file handle with each invocation:
Asynchronously:
const fs = require('fs'); fs.appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('Saved!'); });
Synchronously:
const fs = require('fs'); fs.appendFileSync('message.txt', 'data to append');
Efficient Method: Reusable File Handle
For repeated appends to the same file, it's more efficient to reuse a file handle. This approach involves opening a file handle once, executing multiple appends, and closing the handle when finished:
const fs = require('fs'); const fd = fs.openSync('message.txt', 'a'); // Open file for appending fs.writeSync(fd, 'data to append', null, 'utf-8'); // First append // ... subsequent appends fs.closeSync(fd); // Close file handle
Note on Performance:
For a large number of appends, reusing a file handle significantly enhances performance compared to repeatedly calling appendFile. However, for infrequent appends, the convenience of appendFile may outweigh the performance benefits.
The above is the detailed content of How to Efficiently Append Data to Files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!