Reese Schultz

Coding, gaming and rambling.

Checking File Existence with Node.js

Learn how to check if a file exists with Node.js.

Created on November 16, 2019.

There are two ways to check if a file exists with Node.js. The first is synchronous (blocking), and the second is asynchronous (non-blocking). The difference between the two is explained here if you need a refresher.

In either case, you'll need to include the file system (fs) module like so:

const fs = require('fs')

For the sake of example, let's assume we're checking for a package.json file in the current directory, so we'll set a path variable for that:

const path = 'package.json'

Next, define a couple self-explanatory functions to be explicit:

const fileDoesNotExist = () => {
    // Your logic here.

const fileExists = () => {
    // Your logic here.

Now we're ready to try the synchronous or asynchronous approach.

Synchronous File Check

Synchronous file existence checking is this easy:

fs.existsSync(path) ? fileExists() : fileDoesNotExist()

We leverage the ternary operator to keep things terse.

Asynchronous File Check

Asynchronous file existence checking is slightly more complicated:

fs.access(file, err => err ? fileDoesNotExist() : fileExists())

It's more complicated because there's a callback, which MDN defines as "a function passed into another as an argument," so the existence handling logic should be executed within said callback.

fs.access can also check if a file is readable and writable. To learn more about that, see the official documentation.

© Reese Schultz

My code is released under the MIT license.