Folder Listing in Node.js

0

People need to see all the files in a folder and list it, but calm what I want is to enter the folder and read all the files and list, but if you find a folder between it and list what's in it too . This is by ordering the files by date.

Can anyone help me how? I really tried it in many ways ...

I did this, but I can not sort the files for 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>');
                }
            }
        }
    });
}
    
asked by anonymous 10.11.2018 / 08:29

1 answer

1

You need to sort the array before doing the iterations, I've made a small example below of 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) );
    
10.11.2018 / 18:48