ms_nitrogen ms_nitrogen - 5 months ago 27
Node.js Question

Determine whether file or directory

How would I go about checking on whether a path is either a directory or a file?

var fs = require('fs')
var directory = '/path/to/directory'
var dirContents = fs.readdirSync(directory)
// [".DS_Store", "file01.file", "file02.file", "foo", "bar"]

I understand that node's fs has
, but how do I use those in a loop function to determine what is a file and what is a directory?


If you want to do it sync then its really easy (although maybe not a very good idea).

let contents = fs.readdirSync(dir);
let stats = => {
    return fs.statSync(path.join(dir, dirEntry));
stats.forEach((s) => {
    // isFile is just a function available on the returned stat object

For async, its only slightly different. You'll want to use the async npm library, which takes care of things like this.

let async = require('async');

fs.readdir(dir, (err, contents) => {, (dirEntry, callback) => {
        fs.sync(path.join(dir, dirEntry), callback);
    }, (stats) => {
        // do something with stats array here