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

16,590

Solution 1

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

Solution 2

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')
Share:
16,590

Related videos on Youtube

Shan Khan
Author by

Shan Khan

Masters in Machine Learning, currently working in Data Scientist and Experience of more than 7 years in IT dealing with wide range of applications and platforms, experience within multi-tier environments, analysis, design, consultation and teams leading roles. Delivered/ deployed mission critical applications/ solutions for worldwide customers on highly availability productions environments. Expertise: ➢ Machine Learning and Natural Language Processing ➢ Implementing DevOps process inside Team ➢ Micro services and Azure App Service ➢ Worked in Dynamics 365 Integration Product Development ➢ Worked in SAP HCM Module Product Development ➢ System Analysis and Design More Details on my resume available @ Developer Story

Updated on September 16, 2022

Comments

  • Shan Khan
    Shan Khan over 1 year

    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
        };
    
  • GreeneCreations
    GreeneCreations over 4 years
    This is so awesome, I can't believe (a) that I didn't know this and (b) that this isn't the top answer.
  • Felipe Plets
    Felipe Plets over 4 years
    @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.