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

March 31, 2021 - 1 min read

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 repl.it.

That's it! 😃

Feel free to share if you found this useful 😃.