Nodejs - Asynchronous File Operations with Try-Catch
11/27/2016, SunHandle Situation When File Does Not Exist in Directory
Performing a file reading operation to check whether a file exists before operating might cause a race condition as stated in the Nodejs section on fs.stat:
“Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.”
In order to make it safer when using an asynchronous file read operation, a try-catch block should always wrap the async file operation because it will allow one to handle the situation when a file is indeed non-existent.
Here is an example where the library ‘co’ and ‘fs-extra-promises’ are used to show safe operation with the try-catch block on async operations:
// Log Action of an Observable
import { statAsync } from 'fs-extra-promise';
import co from 'co';
co(function* fileCheck() {
yield co.wrap(function* () {
try {
// statAsync is the promise version of fs.stat
const fileExists = yield statAsync('a/path/that/does/not/exists');
// Check if is a file type of folder type
// Do stuff when the path does exist
// fileExists.isFile() || fileExists.isDirectory()
} catch (e) {
// Errors out here because the path stated does not exists
// Do stuff here where there is an error
// ...
}
};
});