Question

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.

Était-ce utile?

La 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
    }
});

Autres conseils

This is a synchronous version:

var fs = require('fs');

var regex = /^[1-9]\.\d\.\d/;

var folder = __dirname + "/version/";

var files = fs.readdirSync(folder).filter(function(file){

   return regex.test(file) && 
          fs.statSync(folder + file).isDirectory();

})

Revised @Gabriels dynamic answer to suit.
Ended up needing a synchronous solution, inserted before my grunt init. Here is the final code, finding and returning the name of the latest folder version.

var getLatest = function (cwd) {
    var max = false;
    var dirs = fs.readdirSync(cwd);

    if (!dirs.length) {
        //No directories
    } else {
        dirs.forEach(function (dir) {
            if (!max) {
                return max = dir;
            }
            if (semver.gt(dir, max)) {
                max = dir;
            }
        });
    }
    return max;
};

getLatest('build/');

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top