Folder Listing in Node.js

Asked

Viewed 828 times

0

People need to see all the files of a folder and list it, but calm down what I want is to enter the folder and read all the files and list, but if you find a folder enter it and list what is in it too. All this by ordering the files by date.

Can anyone help me how? I’ve really tried many ways...

I did that, but I can’t sort the files by the most recent dates.

function getReports(dir) {
    fs.readdir(dir, function(error, files) {
        for (var i = 0; i < files.length; ++i) {
            var filePath = path.join(dir, files[i]);
            if (fs.statSync(filePath).isDirectory()) {
                getReports(filePath);
            } else {
                var result = files[i].split('.');
                if(result[1].match(/html/))
                {
                    $('.reports').append('<li><a href="#external" data-ext="file:///' + filePath + '">' + result[0] + '</a></li>');
                }
            }
        }
    });
}

1 answer

2


You need to sort the array before making the iterations, I made a small example below what you need.

    const testFolder = './dir'
    const fs = require('fs');

    function readDir(dir){

        let struct = {}

        fs
            .readdirSync(dir)
            .sort((a, b) => fs.statSync(dir +"/"+ a).mtime.getTime() - fs.statSync(dir +"/"+ b).mtime.getTime()) //É AQUI QUE A MÁGICA ACONTECE
            .forEach(file => {

                if( fs.lstatSync(dir+"/"+file).isFile() ){
                    struct[file] = null
                }
                else if( fs.lstatSync(dir+"/"+file).isDirectory() ){
                    struct[file] = readDir(dir+"/"+file)
                }

            })

        return struct

    }

    console.log( readDir(testFolder) );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.