Count files in a directory with nodejs

Jeremy Ikwuje
2 min readMay 1, 2018

--

Credit: Edu Grande — Uplash

In this post, you will learn how to count files in a directory with nodejs.

When working with files and directories, the built in fs module in nodejs provides an api for interacting with the file system. All file system have asynchronous and synchronous nature.

The fs module in Nodejs comes with a method readadir that enable us to read the content in a directory.

The code below get and print the total number of files in a directory.

var fs = require('fs'); fs.readdir( 'path/to/your/folder', (error, files) => { 
let totalFiles = files.length; // return the number of files
console.log(totalFiles); // print the total number of files
});

If your Node.js package does not support JavaScript arrow function, you can use the normal JavaScript function.

var fs = require('fs'); fs.readdir( 'path/to/your/folder', function(error, files) {  
var totalFiles = files.length; // return the number of files
console.log(totalFiles); // print the total number of files
});

Please change the path to your folder to the folder you want to access.

The readdir is a method in fs module.

readdir is asychronous in nature.

It allows three parameters (path[, options], callback).

The first parameter — path is where we specify the path to the folder we want to access.

The second parameter is optional. This is where we specify some option like encoding.

The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

.length is a property for getting the length of an array.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Jeremy Ikwuje
Jeremy Ikwuje

Written by Jeremy Ikwuje

Software Engineer. I write on technology. Follow on Twitter @jeremyikwuje

No responses yet

Write a response