Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Search for folder names higher than X with node

Search for folder names higher than X with node

Problem

I need to get all folders with a name higher than 1.0.0 with node.js

How can i achieve this with the structure below.

|---version
    |--1.0.0
    |--1.2.0
    |--0.9.0

Thanks, am very new to node.

Problem courtesy of: Ricky Boyce

Solution

If the directories have a name that are a valid semver string (like yours) the easiest way is to use the semver module and use the gt function. Something like this:

var greater = function (dir, cb){
    var max = null;
    fs.readdir (dir, function (error, entries){
        if (error) return cb (error);
        if (!entries.length) return cb ();
        entries.forEach (function (entry){
            //Suppose there're no files in the directory
            if (!max) return max = entry;
            if (semver.gt (entry, max)) max = entry;
        });
        cb (null, max)
    });
};

greater ("dir", function (error, dir){
    if (error) return handleError (error);
    if (dir){
        //dir is the greater
    }else{
        //No directories
    }
});
Solution courtesy of: Gabriel Llamas

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Search for folder names higher than X with node

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×