How to use Typescript Async/ await with promise in Node JS FS Module

Shan Khan picture Shan Khan · Feb 27, 2016 · Viewed 12.5k times · Source

How to use Typescript async / await function and return typescript default promises in node js FS module and call other function upon promise resolved.

Following is the code :

  if (value) {
     tempValue = value;
     fs.writeFile(FILE_TOKEN, value, WriteTokenFileResult);
            }

 function WriteTokenFileResult(err: any, data: any) {
        if (err) {
            console.log(err);
            return false;
        }
        TOKEN = tempValue;
        ReadGist(); // other FS read File call
    };

Answer

Felipe Plets picture Felipe Plets · Jun 1, 2019

Since NodeJS 10.0.0 fsPromises module can be used to achieve this result.

import { promises as fsPromises } from 'fs';
await fsPromises.writeFile('file.txt', 'data')