append to a file in typescript

To append data to a file in typescript, you can use the fs.appendFile() method provided by the Node.js fs module.

Here is an example code snippet:

index.ts
import * as fs from 'fs';

const filename = 'example.txt';
const data = 'New content to be appended.\n';

fs.appendFile(filename, data, (err) => {
  if (err) throw err;
  console.log('Data has been appended to the file!');
});
227 chars
10 lines

In the above code, we first import the fs module. We then specify the filename of the file we want to append to (example.txt in this case) and the data that we want to append (New content to be appended.\n). We then use the appendFile() method to append the data to the file.

The appendFile() method takes three parameters:

  1. The filename of the file to append to.
  2. The data to append to the file.
  3. A callback function that will be called after the data has been appended. The callback function takes any potential error as a parameter.

When the appendFile() method is called, the specified data is written to the end of the file, and the callback function is called to signal that the operation is complete.

gistlibby LogSnag