18

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
    };
Shan Khan
  • 9,667
  • 17
  • 61
  • 111

3 Answers3

46

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')
Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
  • 1
    This is so awesome, I can't believe (a) that I didn't know this and (b) that this isn't the top answer. – GreeneCreations Aug 21 '19 at 18:27
  • 1
    @GreeneCreations It's all about timing. My answer came more then two years after Amid answer. The fsPromises was not a reality at that time. – Felipe Plets Aug 21 '19 at 19:05
9

For now I think there is no other way as to go with wrapper function. Something like this:

function WriteFile(fileName, data): Promise<void>
{
    return new Promise<void>((resolve, reject) =>
    {
        fs.writeFile(fileName, data, (err) => 
        {
            if (err)
            {
                reject(err);    
            }
            else
            {
                resolve();
            }
        });
    });        
}

async function Sample()
{
    await WriteFile("someFile.txt", "someData");
    console.log("WriteFile is finished");
}

There is some lengthy discussion here about promises in node.js: Every async function returns Promise

Amid
  • 21,508
  • 5
  • 57
  • 54
0

If you don't want to write the Promise wrappers yourself you can use async-file.

Using this your code could look something like the following...

(async function () {
  //...
  await fs.writeFile(FILE_TOKEN, value);
  var data = await fs.readFile('gist');
  // do something with your "gist" data here...
})();
Dave Templin
  • 1,764
  • 1
  • 11
  • 5