Node.js — Check If a Path Is a File

When interacting with the local hard disk, you may need to check whether an existing path is a file or a directory. Node.js comes with the fs core module providing dozens of useful low-level methods to interact with the hard disk.

This tutorial shows you how to compose an isFile(path) method that helps to check whether a given file path is pointing to a file on the computer’s hard disk.

Node.js Series Overview

Determine Whether a Path Points to a File

Node.js comes with the fs core module. Unfortunately, fs doesn’t expose an isFile method directly. You must build this method yourself using a stats object. The upside: stats comes with Node.js and you can use it like this:

const { promises: Fs } = require('fs')

/**
 * Determine whether a file exists at the given `path`.
 *
 * @param {String} path
 *
 * @returns {Boolean}
 */
async function isFile(path) {  
  const stats = await Fs.stat(path)

  return stats.isFile()
}

await isFile('./package.json')  
// true

await isFile('./node_modules')  
// false

You may be interested in a related tutorial showing you how to check whether a path is a directory.

Use the @supercharge/filesystem Package

I’m the maintainer of the @supercharge/filesystem package providing convenient file system utilities. This package comes with a handy isFile(path) method determining whether the given path points to a file on your local hard disk:

const Fs = require('@supercharge/filesystem')

await Fs.isFile('./package.json')  
// true

await Fs.isFile('./node_modules')  
// false

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.