CodeSnacks

How to check if a file exists in Node.js

July 6, 2019

To check if a file exists using Node.js you can utilize the file system (fs) module. You have two options doing so:

Let’s see how it works in the synchronous/blocking way:

const fs = require('fs')

const path = './file.js'

if (fs.existsSync(path)) {
  console.log("file exists");
} else {
  console.log("file does not exist");
}

If you need to check the existence of a file in an asynchronous/non-blocking manner, then this could help you:

const fs = require("fs");

const path = "./file.js";

fs.access(path, fs.F_OK, err => {
  if (err) {
    console.log("file does not exist");
    return;
  }
  console.log(" file exists");
});