0

fs.writefile is confusing the "alltimeplayers" variable for a different data type than a string. When "alltimeplayers" is logged to console, it is written as a string. The fs is imported with the code var fs = require('fs') Node.JS is installed correctly too.

Am I missing something?

  fs.readFile('players.txt', 'utf8', function(err, data){
      alltimeplayers = data;
      alltimeplayers = parseInt(alltimeplayers);
      alltimeplayers++;
      alltimeplayers = alltimeplayers.toString();
  });
fs.writeFile("books.txt", alltimeplayers, (err) => {
  if (err)
    console.log(err);
});
  • 2
    You're missing the fact that `fs.readFile()` will return *immediately*, before the reading of the file is complete. Thus when `fs.writeFile()` is called, the variable will still be `undefined`. – Pointy Aug 26 '23 at 17:04
  • So how could I fix this? – Mippy Magic Aug 26 '23 at 17:05
  • 1
    Do the `fs.writeFile()` *inside* the callback to `fs.readFile()`. Or, better yet, start using the Promise API which is generally much less confusing to use. – Pointy Aug 26 '23 at 17:06
  • 2
    by either using the promise version and waiting for that to finish, or by putting your file writing code inside the function that readFile calls once it's done. – Mike 'Pomax' Kamermans Aug 26 '23 at 17:06
  • 1
    @MippyMagic initiating the read operation will take at most a couple of **microseconds**, and under no circumstances will the `.readFile()` call wait for the file to be read. It will start the operation and return immediately. – Pointy Aug 26 '23 at 17:07
  • I really have to learn how promises work... – Mippy Magic Aug 26 '23 at 17:07
  • Would setting a timeout work? – Mippy Magic Aug 26 '23 at 17:07
  • 2
    There's barely anything to learn, so: yes. Learning async/await, and the `Promise` concept it's a syntactic sugar for, is absolutely worth doing. As for setting a timeout: _no, why?_ Just put your file write code where it needs to be. Either use promises, _or if you don't want to do that_ just put it inside the function that readFile calls. The one you already have in your code. This is about code flow logic: if you want to write data to a file, put the filewrite in the place where that data exists, which right now is in that callback function you've written. – Mike 'Pomax' Kamermans Aug 26 '23 at 17:07

0 Answers0