Home > Web Front-end > JS Tutorial > How Can I Append Data to a File in Node.js While Preserving Existing Content?

How Can I Append Data to a File in Node.js While Preserving Existing Content?

Susan Sarandon
Release: 2024-11-24 05:33:10
Original
837 people have browsed it

How Can I Append Data to a File in Node.js While Preserving Existing Content?

Preserving Existing File Content: Appending to a File in Node

Appending data to a file in Node while maintaining existing content can be tricky, as demonstrated by the writeFile method's behavior. To overcome this challenge, consider utilizing the appendFile method:

1. Asynchronous Appends with appendFile

const fs = require('fs');

fs.appendFile('message.txt', 'data to append', function (err) {
  if (err) throw err;
  console.log('Saved!');
});
Copy after login

2. Synchronous Appends with appendFileSync

const fs = require('fs');

fs.appendFileSync('message.txt', 'data to append');
Copy after login

These methods perform asynchronous or synchronous appends, respectively, using a new file handle each time they're invoked.

3. File Handle Reuse

However, for frequent appends to the same file, it's recommended to reuse the file handle to enhance efficiency. This can be achieved using the fs.open method:

const fs = require('fs');

fs.open('message.txt', 'a', function(err, fd) {
  if (err) throw err;
  // Append data using the file handle
  fs.write(fd, 'data to append', function(err) {
    if (err) throw err;
  });
  // Close the file handle when finished
  fs.close(fd, function(err) {
    if (err) throw err;
  });
});
Copy after login

The above is the detailed content of How Can I Append Data to a File in Node.js While Preserving Existing Content?. 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