fs.writeFile works but subsequent fs.readFile shows 'old' contents


#1

Environment: Electron 1.6.11 (which includes NodeJS) and Bootstrap 3.3.x for the UI

On the same page of my app I have a button to write to a file via fs.writeFile and also a button to read from that same file via fs.readFile.

After I do a write the subsequent read shows the ‘old’ file contents and not my changes which were just written. It seems that the file contents have been cached which is what the read is seeing.

Question: How to ensure that when I read from the file I get the most recent version of that file?


#2

Are you waiting for writeFile to finish before you try to read it? Both of those methods are asynchronous, so if you don’t have your code structured correctly, it will most likely read the file before it has been successfully written.


#3

Do you have a code stub to show how to wait for writeFile to finish?
Here is my code:

<button type="submit" class="btn btn-success btn-fill" onclick='editFile();'>Save</button>
<button type="submit" class="btn btn-primary btn-fill" onclick='viewFile();'>View</button>

<script language='javascript' type="text/javascript">
function editFile() {
  var fs = require('fs'); 
  var configfile = './myfile.txt';
  var result = 'help wanted';

  fs.writeFile(configfile, result, 'utf8', function (err) {
      if (err) {
        return console.log(err);
      }
   });
}
</script>

<script language='javascript' type="text/javascript">
function viewFile() {
  var fs = require('fs');
  var configfile = './myfile.txt';
  
  fs.readFile(configfile, 'utf8', function (err, data) {
    if (err) {
      alert(err);
    } else {
      alert(data);    
    }
  });
}
</script>

#4

Try fs.writeFileSync


#5

I could not reproduce the issue but went with the suggestion to use

fs.writeFileSync

Thanks