How to check if a file exists synchronously in Node.js?

Published March 31, 2021

To check if a file exists synchronously, you can use the existsSync() method in the fs (filesystem) module in Node.js.

Let's say I want to check whether the path /myFolder/myFile.txt to my file exists or not. Here we can use the fs.existsSync() method and pass the path to the file to check as the first argument to the method

It can be done like this,

// require filesystem module
const fs = require("fs");

// check if file exist
// using fs.existsSync() method
const doesFileExists = fs.existsSync("./myFolder/myFile.txt");

console.log(doesFileExists); // true

See the above code live in

That's it! 😃

Feel free to share if you found this useful 😃.

Share on: Facebook Twitter