Bootstrap FreeKB - Node.js - Determine if file or directory exists using fs.existsSync
Node.js - Determine if file or directory exists using fs.existsSync

Updated:   |  Node.js articles

fs.exists can be used to determine if a file or directory exists asynchronously which basically means that other async logic in the script may run before or after fs.exists.

const fs = require("fs")

const my_file = "/tmp/example.txt"

console.log("before")

if (fs.exists(my_file)) {
  console.log(`${my_file} exists`)
} else {
  console.log((`${my_file} does NOT exist`)
}

console.log("after")

 

Be aware that if you are using a Node.js module instead of CommonJS, you will have "type": "module" in package.json. In this scenario, you will use import instead of require.

import fs from "fs"

 

fs.existsSync can be used to determine if a file or directory exists synchronously which basically means that the script reads like a book, from the top of the script to the bottom of the script, doing things in the order.

import fs from "fs"

const my_file = "/tmp/example.txt"

console.log("before")

if (fs.existsSync(my_file)) {
  console.log(`${my_file} exists`)
} else {
  console.log((`${my_file} does NOT exist`)
}

console.log("after")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter cd1479 in the box below so that we can be sure you are a human.