node.jsfs

Wait until file is created to read it in node.js


I am trying to use file creation and deletion as a method of data transfer (not the best way, I know.) between python and nodejs. The python side of the program works fine, as I am quite familiar with python 3, but I can't get the node.js script to work.

I've tried various methods of detecting when a file is created, mainly with the use of try {} catch {}, but none of them have worked.

function fufillRequest(data) {
  fs.writeFile('Response.txt', data)
}

while(true) {
  try {
    fs.readFile('Request.txt', function(err,data) {
      console.log(data);
    });
  } catch {

  }
}

The program is supposed to see that the file has been created, read it's contents, delete it and then create and write to a response file.


Solution

  • You can either user a recurring timer or fs.watch() to monitor when the file appears.

    Here's what it would look like with a recurring timer:

    const checkTime = 1000;
    const fs = require('fs');
    
    function check() {
       setTimeout(() => {
           fs.readFile('Request.txt', 'utf8', function(err, data) {
              if (err) {
                  // got error reading the file, call check() again
                  check();
              } else {
                  // we have the file contents here, so do something with it
                  // can delete the source file too
              }
           });
       }, checkTime)
    }
    
    check();
    

    Note: Whatever process is creating this file should probably use an exclusive access mode when writing so that you don't create a race condition where it starts reading before the other process is done writing.