node.js – Node: concurrency safe function to ensure directory exists

In node js, how do we make a concurrency safe function to ensure that a directory is created if it doesn’t exist?

This is my version:

const creatingDirectories = new Map();

async function ensureDirectoryExists(targetPath) {
  if (!creatingDirectories.has(targetPath)) {
    const mkdirPromise = fs.promises.mkdir(targetPath, { recursive: true });
    creatingDirectories.set(targetPath, mkdirPromise);
  }

  try {
    await creatingDirectories.get(targetPath);
  } catch (err) {
    console.error(`Error creating directory ${targetPath}:`, err);
    throw err;
  }
}

But I am not very sure of it. Multiple threads can enter first if block and invoke fs.promises.mkdir, isn’t?

PS: I realise node is single threaded, so this may not even be a problem. But I am not sure. To add more context, this function is called for http request processing and there can be simultaneous requests.

Read more here: Source link