write to a file in typescript

To write to a file in TypeScript, you can use the built-in fs module (which is also available in Node.js). Here's an example:

index.ts
import fs from 'fs';

const data = 'Hello, world!';

fs.writeFile('myfile.txt', data, (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Data written to file successfully.');
  }
});
208 chars
12 lines

In this example, we import the fs module and call its writeFile method. The first argument is the filename to write to, the second argument is the data to write, and the third argument is a callback function that will be called once the write operation completes (either successfully or with an error).

If the file exists, its contents will be overwritten. If the file does not exist, it will be created.

gistlibby LogSnag