For a given directory, how can I get a list of files in chronological order (by date-modified) in Node.JS? I didn't see anything in the File System docs.
sort() is an array function from Node. js that is used to sort a given array. Parameter: This function does not takes any parameter. Return type: The function returns the sorted array.
readdir(). It is the same as fs. readdirSync(), but has the callback function as the second parameter.
Steps to get list of all the files in a directory in Node.js Load all the required Nodejs Packages using “require”. Get the path of the directory using path.join () method. Pass the directory path and callback function in fs.readdir (path, callbackFunction) Method.
The simplest way to read a file in Node.js is to use the fs.readFile () method, passing it the file path, encoding and a callback function that will be called with the file data (and the error): Alternatively, you can use the synchronous version fs.readFileSync ():
We will be using Node.js fs core module to get all files in the directory, we can use following fs methods. Loading... fs.readdir (path, callbackFunction) – This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.
In this case Node.js will simply append /joe.txt to the current working directory. If you specify a second parameter folder, resolve will use the first as a base for the second: If the first parameter starts with a slash, that means it's an absolute path:
Give this a shot.
var dir = './'; // your directory
var files = fs.readdirSync(dir);
files.sort(function(a, b) {
return fs.statSync(dir + a).mtime.getTime() -
fs.statSync(dir + b).mtime.getTime();
});
I used the "sync" version of the methods. You should make them asynchronous as needed. (Probably just the readdir
part.)
You can probably improve performance a bit if you cache the stat info.
var files = fs.readdirSync(dir)
.map(function(v) {
return { name:v,
time:fs.statSync(dir + v).mtime.getTime()
};
})
.sort(function(a, b) { return a.time - b.time; })
.map(function(v) { return v.name; });
2021, async/await using fs.promises
const fs = require('fs').promises;
const path = require('path');
async function readdirChronoSorted(dirpath, order) {
order = order || 1;
const files = await fs.readdir(dirpath);
const stats = await Promise.all(
files.map((filename) =>
fs.stat(path.join(dirpath, filename))
.then((stat) => ({ filename, mtime: stat.mtime }))
)
);
return stats.sort((a, b) =>
order * (b.mtime.getTime() - a.mtime.getTime())
).map((stat) => stat.filename);
}
(async () => {
try {
const dirpath = __dirname;
console.log(await readdirChronoSorted(dirpath));
console.log(await readdirChronoSorted(dirpath, -1));
} catch (err) {
console.log(err);
}
})();
a compact version of the cliffs of insanity
solution
function readdirSortTime(dir, timeKey = 'mtime') {
return (
fs.readdirSync(dir)
.map(name => ({
name,
time: fs.statSync(`${dir}/${name}`)[timeKey].getTime()
}))
.sort((a, b) => (a.time - b.time)) // ascending
.map(f => f.name)
);
}
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