How to check if a path is a file in Node.js?

Published December 18, 2020

To check if a path is a file in Node.js, we can use the stat() (asynchronous execution) function or the statSync() (synchronous execution) function from the fs (filesystem) module and then use the isFile() method returned from the stats object.

//  Check if path is a file
fs.statSync("file.txt").isFile();

Let's say we have a file called file.txt inside a directory called reports. Thus the path to the file looks like this,

// require fs module
const fs = require("fs");

// a file path
const path = "./reports/file.txt";

Using the fs.stat() function (Asynchronous Way)

Let's check if the path is a file using the fs.stat() function.

The fs.stat() function needs 2 arguments:

  • The first argument is the path to the file
  • The second argument is an error first callback function that will get executed after reading all the stats about the path.

It can be done like this,

// require fs module
const fs = require("fs");

// a file path
const path = "./reports/file.txt";

// check if path is file using
// the fs.stat() function
fs.stat(path, (error, stats) => {
  // incase of error
  if (error) {
    console.error(error);
    return;
  }

  console.log(stats);

  /*
    Stats {
        dev: 3824,
        mode: 33188,
        nlink: 1,
        uid: 1000,
        gid: 1000,
        ..
        ..
    }
    */
});

In the stats object we can use the isFile() method to check to see if the path is a file or not like this,

// require fs module
const fs = require("fs");

// a file path
const path = "./reports/file.txt";

// check if path is file using
// the fs.stat() function
fs.stat(path, (error, stats) => {
  // incase of error
  if (error) {
    console.error(error);
    return;
  }

  console.log(stats.isFile()); // true
});

See this example live in repl.it.

Using the fs.statSync() function (Synchronous Way)

Let's check if the path is a file using the fs.statSync() function.

The fs.statSync() function needs a path to file as the first argument.

It can be done like this,

// require fs module
const fs = require("fs");

// a file path
const path = "./reports/file.txt";

// check if path is file using
// the fs.statSync() function
const stats = fs.statSync(path);

The function returns an object containing all the stats about the path.

In the stats object we can use the isFile() method to check to see if the path is a file or not like this,

// require fs module
const fs = require("fs");

// a file path
const path = "./reports/file.txt";

// check if path is file using
// the fs.statSync() function
const stats = fs.statSync(path);

console.log(stats.isFile()); // true

See this example live in repl.it.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter