Node.js: how to list and sort files in a directory

In Node.js we can list and sort files in a specific directory.

The sorting order will be determined by the file's creation time obtained using the .statSync() method:


'use strict';

const fs = require('fs');
const path = require('path');
const ABSPATH = path.dirname(process.mainModule.filename); // Absolute path to our app directory

module.exports = {
    listDir: (path) => {
        let files = fs.readdirSync( ABSPATH + path ); // You can also use the async method
        let filesWithStats = [];
        if( files.length > 1 ) {
            let sorted = files.sort((a, b) => {
            let s1 = fs.statSync(ABSPATH + path + a);
            let s2 = fs.statSync(ABSPATH + path + b);
            return s1.ctime < s2.ctime;
        });
        sorted.forEach(file => {
            filesWithStats.push({
                filename: file,
                date: new Date(fs.statSync(ABSPATH + path + file).ctime),
                path: path + file
            });
        });
    } else {
        files.forEach(file => {
            filesWithStats.push({
                filename: file,
                date: new Date(fs.statSync(ABSPATH + path + file).ctime),
                path: path + file
            });
        });
    }
    return filesWithStats;
}
};

Example:


'use strict';
const listing = require('./lib/listing');
const files = listing.listDir('/images');

Output:


 [
   {
     filename: 'image1.jpg',
     date: 'Sat Sep 23 2017 07:47:39 GMT+0200 (CEST)',
     path: '/images/image1.jpg'
   },
   {
     filename: 'image2.png',
     date: 'Sat Sep 20 2017 10:30:12 GMT+0200 (CEST)',
     path: '/images/image1.jpg'
   }
 ]
 
 
Prev Articles Next