Avoiding race conditions when creating or using an existing directory
suggest changeDue to Node’s asynchronous nature, creating or using a directory by first:
- checking for its existence with
fs.stat(), then - creating or using it depending on the results of the existence check,
can lead to a race condition if the folder is created between the check and the creation. The wrappers below call fs.mkdir() and fs.mkdirSync() and ignore EEXIST (already exists). Another error, such as EPERM (permission denied), is thrown or passed on, as the native functions do. An existing file at the same path also raises EEXIST, so this does not prove the path is a directory.
Asynchronous version with fs.mkdir()
var fs = require('fs');
function mkdir(dirPath, callback) {
fs.mkdir(dirPath, (err) => {
callback(err && err.code !== 'EEXIST' ? err : null);
});
}
mkdir('./existingDir', (err) => {
if (err)
return console.error(err.code);
// Do something with `./existingDir` here
});
Synchronous version with fs.mkdirSync()
function mkdirSync(dirPath) {
try {
fs.mkdirSync(dirPath);
} catch (e) {
if (e.code !== 'EEXIST') throw e;
}
}
mkdirSync('./existing-dir');
// Do something with `./existing-dir` now
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents