Home > Blockchain >  async with fs file is not saving
async with fs file is not saving

Time:06-28

I have this code: (i need to use async because this function may be used multiple times per second, so file won't be saved without async)

var fs = require('fs').promises;
async function stater(amount){
   const file = await fs.readFile('stater.txt', function read(err, data) {
      content = Number(data);
      content  =Number(amount);    
      
      if(amount == "clear") content = 0;
      fs.writeFile('stater.txt', content);
      logger.trace("Stater added: "   amount)
   });
   await fs.writeFile('stater.txt', 'test');
}
stater(10000);

But after stater(10000) nothing seems to happen, no errors, but file is not changing. But it works without async, so why so?

CodePudding user response:

It doesn't work because you're using a callback for fs.readFile() which won't get called because you're using the Promise-based version.

You need to use promises all the way:

const data = await fs.readFile('stater.txt');
let content = Number(data);
content  =Number(amount);    
  
if(amount == "clear") content = 0;
await fs.writeFile('stater.txt', content);
logger.trace("Stater added: "   amount)

CodePudding user response:

First of all, you declared starter function to be asynchronous. Just declaring it to be asynchronous is not enough. It should be called another (async) function and you should use the await keyword before it. You can also use IIFE (Immediately Invoked Function Expression). Example:

var fs = require('fs').promises;
async function stater(amount){
   const file = await fs.readFile('stater.txt', function read(err, data) {
      content = Number(data);
      content  =Number(amount);    
      
      if(amount == "clear") content = 0;
      fs.writeFile('stater.txt', content);
      logger.trace("Stater added: "   amount)
   });
   await fs.writeFile('stater.txt', 'test');
}

(async () => {
  await stater(10000);
})();

Few other things I noticed:

  1. Have you declared content variable somewhere?
  2. Do you know that typeof data will be a string? Number(string) may not work as you intended.
  • Related