KKitForma.

Language

EnglishEnglishTürkçeTurkishGuide unavailable in this language · open toolsDeutschGermanGuide unavailable in this language · open toolsEspañolSpanishGuide unavailable in this language · open toolsFrançaisFrenchGuide unavailable in this language · open toolsPortuguêsPortugueseGuide unavailable in this language · open toolsItalianoItalianGuide unavailable in this language · open toolsNederlandsDutchGuide unavailable in this language · open toolsPolskiPolishGuide unavailable in this language · open toolsРусскийRussianGuide unavailable in this language · open toolsУкраїнськаUkrainianGuide unavailable in this language · open toolsSvenskaSwedishGuide unavailable in this language · open toolsNorskNorwegianGuide unavailable in this language · open toolsDanskDanishGuide unavailable in this language · open toolsSuomiFinnishGuide unavailable in this language · open toolsČeštinaCzechGuide unavailable in this language · open toolsRomânăRomanianGuide unavailable in this language · open toolsΕλληνικάGreekGuide unavailable in this language · open toolsالعربيةArabicGuide unavailable in this language · open toolsעבריתHebrewGuide unavailable in this language · open toolsفارسیPersianGuide unavailable in this language · open toolsاردوUrduGuide unavailable in this language · open toolsहिन्दीHindiGuide unavailable in this language · open toolsবাংলাBengaliGuide unavailable in this language · open toolsதமிழ்TamilGuide unavailable in this language · open toolsతెలుగుTeluguGuide unavailable in this language · open toolsमराठीMarathiGuide unavailable in this language · open toolsગુજરાતીGujaratiGuide unavailable in this language · open tools简体中文Chinese SimplifiedGuide unavailable in this language · open tools繁體中文Chinese TraditionalGuide unavailable in this language · open tools日本語JapaneseGuide unavailable in this language · open tools한국어KoreanGuide unavailable in this language · open toolsTiếng ViệtVietnameseGuide unavailable in this language · open toolsไทยThaiGuide unavailable in this language · open toolsBahasa IndonesiaIndonesianGuide unavailable in this language · open toolsBahasa MelayuMalayGuide unavailable in this language · open toolsFilipinoFilipinoGuide unavailable in this language · open toolsKiswahiliSwahiliGuide unavailable in this language · open toolsAfrikaansAfrikaansGuide unavailable in this language · open toolsMagyarHungarianGuide unavailable in this language · open toolsБългарскиBulgarianGuide unavailable in this language · open toolsHrvatskiCroatianGuide unavailable in this language · open toolsSrpskiSerbianGuide unavailable in this language · open toolsSlovenčinaSlovakGuide unavailable in this language · open toolsSlovenščinaSlovenianGuide unavailable in this language · open toolsLietuviųLithuanianGuide unavailable in this language · open toolsLatviešuLatvianGuide unavailable in this language · open toolsEestiEstonianGuide unavailable in this language · open toolsCatalàCatalanGuide unavailable in this language · open toolsEuskaraBasqueGuide unavailable in this language · open tools
← Questions & answers

KITFORMA · EDITORIAL ANSWER

Why is checking fs.exists before opening a file unreliable?

KitForma editorial guide. Attempt file creation with the exclusive wx flag and handle EEXIST instead of checking existence and then writing.

Node.js, HTTP & APIs →

Step-by-step answer

A file can appear between an existence check and a write. Ask the filesystem to perform the intended operation directly. This example starts two exclusive creation attempts against one temporary path and reports the winner and conflict. Runnable example:
javascript
import { mkdtemp, open, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const directory = await mkdtemp(join(tmpdir(), "kitforma-exclusive-"));
const path = join(directory, "result.txt");
async function createOnce(label) {
  let handle;
  try {
    handle = await open(path, "wx");
  } catch (error) {
    if (error.code === "EEXIST") return false;
    throw error;
  }
  try { await handle.writeFile(label, "utf8"); }
  finally { await handle.close(); }
  return true;
}
try {
  const outcomes = await Promise.all([createOnce("first"), createOnce("second")]);
  console.log("created:", outcomes.filter(Boolean).length);
  console.log("conflicts:", outcomes.filter(value => !value).length);
  console.log("complete content:", ["first", "second"].includes(await readFile(path, "utf8")));
} finally {
  await rm(directory, { recursive: true, force: true });
}
Expected result:
text
created: 1
conflicts: 1
complete content: true
Why it works: The exclusive open combines the missing-file condition with creation, so a second creator gets EEXIST instead of overwriting the first file. Permission errors and disk failures are rethrown. The winning label is intentionally unspecified because scheduling is nondeterministic. Scope and checks: Run as a Node.js 24 ES module on a local filesystem. Exclusive creation can have limitations on network filesystems. A file can exist before its writer finishes, so this is not an atomic publication protocol for readers. For replacing a complete configuration use a temporary sibling and a suitable rename; concurrent updates still need coordination. Related tools and guides: Complete-file replacement example in Python: https://kitforma.com/en/community/questions/7aa10000-0000-4000-8000-000000007520/ Locate a module’s sidecar file: https://kitforma.com/en/community/questions/7aa10000-0000-4000-8000-000000008380/ Primary sources (reviewed 2026-10-08): Node.js 24 — fsPromises.open and file system flags: https://nodejs.org/docs/latest-v24.x/api/fs.html#fspromisesopenpath-flags-mode

Sources and verification

Sources checked:

This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.

Discussion and community answers

Loading community…
KitForma

What would you like to do?