read a file in typescript

To read a file in TypeScript, you can use the built-in fs module in Node.js. Here is an example that demonstrates how to read a file, decode the contents as UTF-8, and log the result to the console:

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

const filePath = '/path/to/your/file.txt';

fs.readFile(filePath, 'utf-8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});
197 chars
12 lines

In the code above, we first import the fs module from Node.js. We then specify the path to the file that we want to read in the filePath constant. We use the fs.readFile method to read the contents of the file, specifying 'utf-8' as the encoding to use. The result is passed to a callback function that logs the data to the console.

Note that fs.readFile returns the file contents as a Buffer if no encoding is specified. If you want to work with the file contents as a Buffer, omit the encoding parameter:

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

const filePath = '/path/to/your/file.txt';

fs.readFile(filePath, (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data.toString('utf-8'));
});
206 chars
12 lines

In this case, we use data.toString('utf-8') to convert the Buffer to a string before logging it to the console.

gistlibby LogSnag