Home > Web Front-end > JS Tutorial > How to Efficiently Append Data to a File in Node.js?

How to Efficiently Append Data to a File in Node.js?

Linda Hamilton
Release: 2024-11-25 08:08:33
Original
181 people have browsed it

How to Efficiently Append Data to a File in Node.js?

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!');
});
Copy after login

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:

  1. Open the file:
const fs = require('fs');

const fd = fs.openSync('message.txt', 'a');
Copy after login
  1. Write to the file:

Use fs.write() to append data to the file.

fs.write(fd, 'data to append', null, 'utf8', function(err, written, buffer) {});
Copy after login
  1. Close the file:
fs.closeSync(fd);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template