HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to append to a file in Node?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
appendhowfilenode

Problem

I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.

fs.writeFile('log.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'


Any idea how to do this the easy way?

Solution

For occasional appends, you can use appendFile, which creates a new file handle each time it's called:

Asynchronously:

const fs = require('fs');

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


Synchronously:

const fs = require('fs');

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


But if you append repeatedly to the same file, it's much better to reuse the file handle.

Code Snippets

const fs = require('fs');

fs.appendFile('message.txt', 'data to append', function (err) {
  if (err) throw err;
  console.log('Saved!');
});
const fs = require('fs');

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

Context

Stack Overflow Q#3459476, score: 1189

Revisions (0)

No revisions yet.