Node.js
existsSync
Learn to check file existence with fs.existsSync.
What is existsSync?
fs.existsSync checks synchronously whether a file or folder exists, returning true or false. It has no counterpart in fs/promises; it is a direct method of fs.
import { existsSync } from 'fs';
if (existsSync('notes.txt')) {
console.log('exists');
}
Here existsSync checks the file existence instantly. It is imported from the classic fs module and does not return a Promise. An asynchronous alternative is fs.promises.access, but existsSync is short and simple.
existsSync and race conditions
Although existsSync checks file existence, it does not guarantee the file is readable; permissions may block it. So if you check and then call readFile immediately, a race condition can occur: the file may be deleted between the two calls.
if (existsSync('a.txt')) {
// the file may be deleted here
const data = await fs.readFile('a.txt', 'utf8');
}
So in most cases it is safer to call readFile directly and catch the ENOENT error. Still, for simple cases like checking whether a config file exists, existsSync is practical.
Exercise Your turn: check with existsSync
Import the modules with import fs from 'fs/promises' and import { existsSync } from 'fs'. Define an async function run(). Inside, first write await fs.writeFile('check.txt', 'data'). Then check with if (existsSync('check.txt')) and log console.log('exists'). Call run().
Show example solution
import fs from 'fs/promises';
import { existsSync } from 'fs';
async function run() {
await fs.writeFile('check.txt', 'data');
if (existsSync('check.txt')) {
console.log('exists');
}
}
run();
Test yourself
-
What does fs.existsSync return?
- true or false
- A Promise
- The file content
- An error object
Show answer
true or false — existsSync returns true or false.
-
Fill in the blank: existsSync
import { existsSync } from 'fs';
if (____('notes.txt')) {
console.log('exists');
}
Show answer
import { existsSync } from 'fs';
if (existsSync('notes.txt')) {
console.log('exists');
}
-
existsSync concepts
- existsSync
- checks existence
- synchronous
- returns immediately
- true
- file exists
Next lesson: Summary - fs module