-
-
Save sebastianbachmann/cf2a0954d8ada331e18183726f01dc96 to your computer and use it in GitHub Desktop.
Get the most recently changed file in NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path'); | |
var fs = require('fs'); | |
var getMostRecent = function (dir, cb) { | |
var dir = path.resolve(dir); | |
var files = fs.readdir(dir, function (err, files) { | |
var sorted = files.map(function(v) { | |
var filepath = path.resolve(dir, v); | |
return { | |
name:v, | |
time:fs.statSync(filepath).mtime.getTime() | |
}; | |
}) | |
.sort(function(a, b) { return b.time - a.time; }) | |
.map(function(v) { return v.name; }); | |
if (sorted.length > 0) { | |
cb(null, sorted[0]); | |
} else { | |
cb('Y U NO have files in this dir?'); | |
} | |
}) | |
} | |
getMostRecent('./', function (err, recent) { | |
if (err) console.error(err); | |
console.log(recent); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment