ms_nitrogen ms_nitrogen - 4 months ago 13
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
fs.Stats
with
stat.isFile
and
stat.isDirectory
, but how do I use those in a loop function to determine what is a file and what is a directory?

Answer

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 = contents.map((dirEntry) => {
    return fs.statSync(path.join(dir, dirEntry));
});
stats.forEach((s) => {
    // isFile is just a function available on the returned stat object
    console.log(s.isFile());
});

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) => {
    async.map(contents, (dirEntry, callback) => {
        fs.sync(path.join(dir, dirEntry), callback);
    }, (stats) => {
        // do something with stats array here
    });
});
Comments