write a text file in javascript

To write text to a file in Javascript, you first need to create a file object with the File constructor. Then, you can create a FileWriter object to write to the file. Here's an example:

index.tsx
let file = new File(["Hello, world!"], "example.txt");

let writer = new FileWriter();

writer.write(file);
108 chars
6 lines

In this example, we're creating a file object with the contents "Hello, world!" and a filename of "example.txt". We're then creating a FileWriter object and calling its write() method with the file object as the parameter. This will write the contents of the file object to a file with the specified filename.

Note that in Node.js, you'll need to use the fs module to access the file system. Here's an example of how to write to a file in Node.js:

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

fs.writeFile('example.txt', 'Hello, world!', function(err) {
  if (err) throw err;
  console.log('File saved!');
});
144 chars
7 lines

In this example, we're using the writeFile() method of the fs module to write the string "Hello, world!" to a file named "example.txt". We're also providing a callback function to handle any errors that may occur during the write.

gistlibby LogSnag