Check if a file exists with Node.js
Published on
NaNTo check if a file exists in the filesystem using Node.js, you can use the fs.existsSync
method.
import { existsSync } from 'node:fs'; if (existsSync('/etc/passwd')) { console.log('The path exists.'); }
This method is synchronous, which means it’s blocking. If you want to check if a file exists without opening it, you can
use fs.access
.
import { access, constants } from 'node:fs'; const file = 'package.json'; access(file, constants.F_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); });