How can I check if the folder/file exist before read and write to the file? I did some search and it shows that using "fs.stat() or fs.access() to check if a folder/file exists" but I also read some related questions (related question one, related question two) and it appears to be that I might get some kind of "race condition".
I am thinking of doing below approach to avoid "race condition", am I still going to get some kind of "race condition" with below approach?:
const checkIfFolderOrFileExist = () => {
  return new Promise((resolve, reject) => {
    fs.access(filePath, constants.F_OK, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve("exist");
      }
    });
  });
};
const createFolder = () => {
  return new Promise((resolve, reject) => {
    fs.mkdir(folderPath, { recursive: false }, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve("done");
      }
    });
  });
};
const writeToTheFile = (data) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(filePath, data, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve("Done");
      }
    });
  });
};
const callBothPromiseFunction = async () => {
  /* Does below code has a possibility that I might get some kind of "race condition"? (I am using fs.access and fs.writeFile) */
  const folderOrFileExist = await checkIfFolderOrFileExist(); //<---- using fs.access
  if (folderOrFileExist === "exist") {
    const response = await writeToTheFile(someRandomData);
    /* some other js codes */
  } else {
    await createFolder();
    const response = await writeToTheFile(someRandomData);
    /* some other js codes */
  }
};
 
     
     
    