Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a file exists in Node.js

Short answer

existsSync() from node:fs returns true or false:

import { existsSync, writeFileSync } from 'node:fs';
 
writeFileSync('config.json', '{}');
 
console.log(existsSync('config.json'));
console.log(existsSync('missing.json'));

Output:

true
false

With promises

In async code, access() throws an error if the file is missing:

import { access, writeFile } from 'node:fs/promises';
 
const exists = async (path) => {
  try {
    await access(path);
    return true;
  } catch {
    return false;
  }
};
 
await writeFile('data.txt', '');
console.log(await exists('data.txt'), await exists('nope.txt'));

Output:

true false

A file or a folder

stat() tells what the path points to:

import { mkdir, stat, writeFile } from 'node:fs/promises';
 
await mkdir('uploads', { recursive: true });
await writeFile('uploads/photo.jpg', 'abc');
 
console.log((await stat('uploads')).isDirectory());
console.log((await stat('uploads/photo.jpg')).isFile());

Output:

true
true

Common mistake

Checking first and reading second leaves a gap: the file can disappear in between. If you are going to read the file anyway, just read it and handle the ENOENT error:

import { readFile } from 'node:fs/promises';
 
const text = await readFile('settings.txt', 'utf8').catch((error) => {
  if (error.code === 'ENOENT') return 'default settings';
  throw error;
});
 
console.log(text);

Output:

default settings

Functions used in this recipe

  • try...catch — Catches errors so the program does not stop.

Thanks for reading!

Donate to the site — we work hard for you.