existsSync
- Node.js course
- Beginner
- Lesson 104/116
- 5 min
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.
Practice 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().
Starter code
// Import fs/promises and fs modules
// Define async function run
// Create file with writeFile, check with existsSync, log with console.log
// Call runSample 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();Expected output
exists
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does fs.existsSync return?
- true or false Correct answer
- A Promise
- The file content
- An error object
Explanation: existsSync returns true or false.
2 Fill in the blank: existsSync
import { existsSync } from 'fs';
if (____('notes.txt')) {
console.log('exists');
}
import { existsSync } from 'fs';
if (existsSync('notes.txt')) {
console.log('exists');
}
Explanation: You check existence with existsSync.
3 existsSync concepts
| Term | Meaning |
|---|---|
existsSync |
checks existence |
synchronous |
returns immediately |
true |
file exists |