Reputation: 423
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.
Upvotes: 29
Views: 29983
Reputation: 1062
Use this package npm i readdir-life
.
readdirLife.oldest(dir)
.then(res => console.log(res))
.catch(err => console.error(err));
Upvotes: -1
Reputation: 53
The solution with the streams works well. But incase you do not want to use streams, you may use statsSync as follows:
//import the fs
const fs = require("fs");
//list with statSync
//I added letters at the start of the files names so that the alphabetical order becomes different from the chronollogical
fs.readdir("./anville95/", (error, files) => {
if(error) {
console.log("Sorry lad, I was unable to read the files!");
return;
}
console.log("Before sorting with the last modification time...");
console.log(files);
//compare each file with each and every file using their milliseconds modification time and swap if necessary
for(var i = 0; i < files.length; i++) {
for(var j = 0; j < files.length; j++) {
//create the stats files
var firstFileStats = fs.statSync("./anville95/" + files[i]);
var secondFileStats = fs.statSync("./anville95/" + files[j]);
//if files[i] comes before files[j] and files[i] modification time is older than files[j] modification time, swap them
if(i < j && firstFileStats.mtimeMs > secondFileStats.mtimeMs) {
var swap = files[i];
files[i] = files[j];
files[j] = swap;
}
}
}
//At this point, the swapping is done thus I print out the results
console.log("After sorting chronollogically with statSync().mtimeMs...");
console.log(files);
});
Here are the screenshots I took of my results during its execution. Thank you for reading, happy coding.
Upvotes: 1
Reputation: 3201
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);
};
getSortedFiles(myDir)
.then(console.log)
.catch(console.error);
Upvotes: 78
Reputation: 423
I have got the answer using sorting operation.
fs.stat(path, function (err, stats) {
res.push(file.substring(0, file.length - 5) + '&' + stats.mtime);
});
stored mtime to an array and sort that array using sorting technique in below url.
Upvotes: -4