Need to read list of files from particular directory with Date modified by descending or ascending in Node js.
I have tried below code but could not get the solution.
fs.readdir(path, function (err, files) {
if (err) throw err;
else {
var res = [];
files.forEach(function (file) {
if (file.split('.')[1] == "json") {
fs.stat(path, function (err, stats) {
});
res.push(file.substring(0, file.length - 5));
}
});
}
stats parameter give mtime as modified time?
Is there any way to get files with modified date.
mtime
gives Unix timestamp. You can easily convert to Date as,const date = new Date(mtime);
And for your sorting question, you can do as following
var dir = 'mydir/';
fs.readdir(dir, function(err, files){
files = files.map(function (fileName) {
return {
name: fileName,
time: fs.statSync(dir + '/' + fileName).mtime.getTime()
};
})
.sort(function (a, b) {
return a.time - b.time; })
.map(function (v) {
return v.name; });
});
files
will be an array of files in ascending order.
For descending, just replace a.time
with b.time
, like b.time - a.time
UPDATE: ES6+ version
const myDir = 'mydir';
const getSortedFiles = async (dir) => {
const files = await fs.promises.readdir(dir);
return files
.map(fileName => ({
name: fileName,
time: fs.statSync(`${dir}/${fileName}`).mtime.getTime(),
}))
.sort((a, b) => a.time - b.time)
.map(file => file.name);
};
Promise.resolve()
.then(() => getSortedFiles(myDir))
.then(console.log)
.catch(console.error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With