Home > Net >  How can I use Node.js fs to sort a set of folders according to their created date?
How can I use Node.js fs to sort a set of folders according to their created date?

Time:01-01

I'm building a node.js application in which I need to read all the folders in a parent folder and display their names in the order they were created on the page. Here is what I have so far:


function getMixFolders() {
    const { readdirSync } = require('fs');
    
    const folderInfo = readdirSync('./shahspace.com/music mixes/')
        .filter(item => item.isDirectory() && item.name !== 'views');
    
    return folderInfo.map(folder => folder.name);
}

As you can see, I haven't implemented sorting. This is because readdirSync doesn't return the information I need. The only things it returns are the name of the folder and something called the Symbol(type) (which seems to indicate whether its a folder or file).

Is there another method for getting more details about the folders I'm reading from the parent folder? Specifically the created date?

CodePudding user response:

There is no super efficient way in nodejs to get a directory listing and get statistics on each item (such as createDate). Instead, you have to distill the listing down to the files/folders you're interested in and then call fs.statSync() (or one of the similar variants) on each one to get that info. Here's a working version that looks like it does what you want:

  1. Get directory list using the {withFileTypes: true} option
  2. Filter to just folders
  3. Ignore any folders named "views"
  4. Get createDate of each folder
  5. Sort the result by that createDate in ascending order (oldest folders first)

This code can be run as it's own program to test:

const fs = require('fs');
const path = require('path');

const mixPath = './shahspace.com/music mixes/';

function getMixFolders() {
    const folderInfo = fs.readdirSync(mixPath, { withFileTypes: true })
        .filter(item => item.isDirectory() && item.name !== 'views')
        .map(folder => {
            const fullFolderPath = path.join(path.resolve(mixPath), folder.name);
            const stats = fs.statSync(fullFolderPath);
            return { path: fullFolderPath, ctimeMs: stats.ctimeMs }
        }).sort((a, b) => {
            return a.ctimeMs - b.ctimeMs;
        });
    return folderInfo;
}

let result = getMixFolders();
console.log(result);

If you wanted the final array to be only the folder names without the createDates you could add one more .map() to transform the final result.

  • Related