I have a list of files I'd like convert, recreating the original nested directory structure. I'm using the promises version of the fs module and use asynchronous code as much as possible. My current code looks like this:
import fs from 'fs/promises';
import path from 'path';
const sourceFiles = [
// big list of file paths here
];
const allDone = Promise.all( sourceFiles.map( async (srcFile) => {
const destFile = path.join('dest', srcFile);
const destDir = path.dirname(destFile);
// Async existence check with 'access' in try/catch block, since we don't have fs.exists
try {
await fs.access(destDir);
} catch (e) {
await fs.mkdir(destDir);
}
return myConversionFunction( srcFile, destFile);
} ) );
I'm getting errors that the directory already exists, probably because there is a race condition between fs.access and fs.mkdir when running several Promises "in parallel".
I could solve this by calling mkdir with {recursive: true}, but that would try to create the directory on every file.
I could also iterate over the file list twice, creating a list of target directories and then just map over myConversionFunction. But that feels inefficient for big file lists.
Is there a better way to conditionally create directories?