read a text file in javascript

To read a text file in JavaScript, you can use the File System module in Node.js. Here's an example:

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

fs.readFile('myfile.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
125 chars
7 lines

In this code, we first import the Node.js fs module, which allows us to work with the file system. We use the readFile function to read the contents of 'myfile.txt'. The second argument, 'utf8', specifies the file encoding.

The third argument is a callback function that is called when the file has been read. If there is an error (e.g. the file does not exist), err will be set. Otherwise, data will contain the contents of the file as a string. In this example, we simply log the contents of the file to the console.

Note that this example code is for Node.js. If you want to read a file in the browser, you'll need to use a different approach (e.g. XMLHttpRequest).

gistlibby LogSnag