async read file in typescript

To read a file asynchronously in TypeScript, you can use the fs module which is a built-in module in Node.js. You can use the fs.readFile() method to read a file asynchronously. Here's an example:

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

async function readFileAsync(filePath: string): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    fs.readFile(filePath, { encoding: 'utf-8' }, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

async function main() {
  try {
    const data = await readFileAsync('/path/to/file.txt');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

main();
483 chars
25 lines

In this example, we define an async function readFileAsync that takes a filePath parameter and returns a Promise<string>. The file is read with fs.readFile, which reads the entire contents of a file asynchronously. We wrap it with a Promise and return it with resolve once the file is read successfully, or with reject in case of an error.

Then, we define another async function main to execute the readFileAsync function, and log the result to the console.

We can execute this by calling the main function, which returns a Promise that resolves with the contents of the file. We use await to wait for the Promise to resolve before logging the contents to the console.

gistlibby LogSnag