skip to content

Node's fs docs warn against calling fs.access() before fs.open(); in an upload service, what replaces that check, and which error codes do you handle?

level: seniorimportance: should knowfreq 40%

answer

  1. the answer can change between calls
  2. let the open itself decide
  3. exclusive flags and EEXIST
  4. stat the handle, not the name

basics

~10 s

Between an fs.access() or stat check and the open, another process can change the file. Open directly instead: 'wx' to create only if absent (EEXIST), 'r' to read (ENOENT), then stat the opened FileHandle.

solid answer

~40 s

A check followed by an action is two calls, and the file can be created, deleted or swapped between them, so the check proves nothing about the open. Node's fs reference says so for `fs.access()` and recommends opening directly and handling the error. In an upload service that must not overwrite an existing upload, use `open(target, 'wx')` or `writeFile(target, data, { flag: 'wx' })`; the create fails with `EEXIST` if the name is taken, so retry with a new name. For reads, open with `'r'` and map `ENOENT` to 404 and `EACCES` to 403. Facts you need after opening, such as size or type, come from `filehandle.stat()`, which describes the file you actually hold. To replace a file, write a temporary file in the same directory and `rename` it over the target.

code

javascript · 27 lines
javascript
import { mkdir, open, unlink } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import path from 'node:path';

export async function saveUpload(userDir, ext, data) {
  await mkdir(userDir, { recursive: true });
  for (let attempt = 0; attempt < 3; attempt++) {
    const target = path.join(userDir, `${randomUUID()}${ext}`);
    let fh;
    try {
      fh = await open(target, 'wx'); // create only if absent: no separate check
    } catch (err) {
      if (err.code === 'EEXIST') continue; // name taken: try another
      throw err;
    }
    let written = false;
    try {
      await fh.writeFile(data);
      written = true;
      return target;
    } finally {
      await fh.close();
      if (!written) await unlink(target).catch(() => {}); // leave no partial file
    }
  }
  throw new Error('could not allocate a file name');
}

go deeper

for a junior

Recall that checking whether a file exists and then opening it is two calls, and that 'wx' creates a file only if it is absent.

for a middle

Explain why the gap between check and open is a race, which error codes the direct open raises, and why stat on the FileHandle beats stat on the path.

for a senior

Design the upload path: exclusive create with retry on EEXIST, temp-then-rename for replacement, per-path write serialisation and the network file system caveat.

for a principal

Set the team rule that existence checks never gate file operations, and make the open-and-handle-errors helper the only way services touch user files.

## The pattern Node's documentation warns about A **time-of-check to time-of-use** race happens when code checks a property of a file and then acts on it in a separate call. The general theory sits with concurrency fundamentals; what matters here is how Node's API invites it and how Node's API fixes it. The fs reference is explicit: using `fs.access()` to check a file before `fs.open()`, `fs.readFile()` or `fs.writeFile()` **introduces a race condition**, because other processes may change the file's state between the two calls. The same holds for `fs.stat()` and for `fs.existsSync()`. (`fs.exists()` is deprecated; `fs.existsSync()` is not, but it has the identical race.) The recommended code opens, reads or writes directly and **handles the error**. ## Creating a file without overwriting one Picture a service that stores uploads under a per-user directory and must never overwrite an existing file: 1. Ensure the directory exists with `mkdir(dir, { recursive: true })`, which does not reject when the directory already exists. 2. Create the file with an **exclusive flag**: `open(target, 'wx')`, or `writeFile(target, data, { flag: 'wx' })`. `'wx'` is like `'w'` but fails if the path exists. 3. On `EEXIST`, pick another name and try again; any other error propagates. The exclusive flag maps to `O_EXCL` in open(2), so the existence check and the create are a **single operation**. Two requests racing for the same name cannot both succeed. The fs docs add two caveats: on POSIX, `O_EXCL` fails even when the path is a symbolic link to a file that does not exist, and the exclusive flag **might not work on network file systems**. ## Reading and inspecting what you opened For downloads, skip the existence check and open with `'r'`: | Error code | Meaning | Typical response | |---|---|---| | `ENOENT` | the path does not exist | 404 | | `EACCES` | permission denied | 403 or 500 | | `EISDIR` | the path is a directory | 400 or 404 | | `EEXIST` | an exclusive create found an existing path | retry with a new name | | `EMFILE` | the process is out of file descriptors | 503, then look for a handle leak | If the code needs facts about the file, such as its size for a limit or whether it is a regular file, take them from **`filehandle.stat()`** after opening. It describes the open file itself, so a rename or replacement of the name afterwards does not change what you are reading. `fsPromises.stat(path)` before the open describes whatever the name pointed at a moment earlier. ## Replacing a file When an upload legitimately replaces an older one, writing in place with `'w'` truncates the old content first, so a reader can see a half-written file. Instead: - write the new content to a unique temporary name in the **same directory**, - then `rename(tmp, target)`; the fs reference states that an existing file at the new path is overwritten. POSIX defines a rename within one file system as a single replacement, so readers see either the old file or the new one; the Node reference itself only promises the overwrite. Use `mkdtemp(prefix)` when you need a private scratch directory; it appends six random characters to the prefix. ## Putting the upload path together 1. Build the target with `path.join(userDir, generatedName)`; never let the stored name be the client's raw file name. 2. Open it once with `'wx'` and keep the returned `FileHandle` for every later step: write through `fh.writeFile()` or a stream from the handle, check limits with `fh.stat()`, then close it in `finally`. 3. On `EEXIST`, generate a new name and loop a bounded number of times. 4. If the write fails half-way, remove the partial file with `unlink` before reporting the error, so a retry does not collide with debris. ## Rules that follow - An existence or permission check before an operation is a **hint for the user interface**, never a guarantee; the docs suggest checking accessibility only when the file will not be used directly. - `fs.access()` also misses Windows ACLs, so it can report a path as accessible that the open will then refuse. - Promise and callback fs calls are **not synchronized**: two concurrent writes to the same path from your own process can interleave. Serialise writes per path, or give each request its own file. - Validating the shape of a user-supplied name, and the attack class that explains why, are covered with path traversal in the application-security material; the open-and-handle pattern here holds regardless.

  • When is calling fs.access() still legitimate in a Node service?
    When the file will not be used right afterwards and its accessibility is itself the signal, which is the case the fs docs carve out: a readiness probe confirming a mounted secret is readable, or a startup check that fails fast with a clear message. The later real open must still handle errors.
  • The uploads directory sits on a network file system. What changes?
    The fs docs warn that the exclusive flag might not work on network file systems, so `'wx'` may not give a reliable create-if-absent. Generate names that cannot collide, such as a random UUID, so uniqueness does not rest on `O_EXCL`, and write through a temporary name and `rename`.

  • Checking fs.existsSync() right before open() makes the open safe
  • fs.access() succeeding guarantees the next fs.open() succeeds
  • Opening with 'w' is fine for uploads because it creates the file if needed
  • fsPromises.stat(path) before opening describes the file you will read
  • Node serialises concurrent fs/promises writes to the same file