append to a file in javascript

To append to a file in Node.js, you need to use the fs (file system) module.

Here is an example code snippet that appends text to a file:

index.tsx
const fs = require('fs');

fs.appendFile('file.txt', 'new data to append', function (err) {
  if (err) throw err;
  console.log('Data appended to file!');
});
159 chars
7 lines

The function appendFile takes three parameters: the name of the file you want to append to, the data you want to append, and a callback function that is called after the data is appended. If an error occurs, it will be passed to the callback function. Otherwise, the message "Data appended to file!" will be logged to the console.

Note: appendFile will create the file if it doesn't already exist. If the file does exist, it will add the new data to the end of the file.

related categories

gistlibby LogSnag