Tuesday, 18 April 2017

Node.js: fs.readdir does not return a file written by fs.writeFile

My app

A simple Node.js http server which creates files in a given directory by calling POST /deploy. After the file is written, I want to list all the files in that directory using console.log.

For creating files (POST /deploy), I call:

fs.writeFile(filename, content, 'utf8', callback(null, {'newFile': filename})); 

The callback writes the HTTP response and lists the files using:

fs.readdir(some_directory, (err, files) => {
    files.forEach(file => {
        console.log(file);
        // Do something with the file
    }
}

My problem

The new file is not listed in the callback. Only after I call deploy again, the previous file is listed. For example, if I create files a and b using /deploy consecutively, a is listed only when b is created and b is not listed until I make another call.

I assume the file is not closed when the callback is called, so that only later calls to fs.readdir see the file, after it has been closed.

How can I call the callback function only after the file is properly closed and can be listed using fs.readdir?

What have I tried

  • Reading the fs.close() manual. It requires an fd, not a filename, so I have to open the files just for closing it, which seems cumbersome.
  • Searching for similar problems in SO


via Adam Matan

No comments:

Post a Comment