How do I go through a folder and find out which is the newest created/modified file and put the full path of it into a var as string?
Haven't really figured out io/best practices for io
How do I go through a folder and find out which is the newest created/modified file and put the full path of it into a var as string?
Haven't really figured out io/best practices for io
Share Improve this question asked Jun 8, 2012 at 22:28 jmoonjmoon 5763 gold badges7 silver badges18 bronze badges5 Answers
Reset to default 6Take a look at http://nodejs/api/fs.html#fs_class_fs_stats
look at the ctime
or mtime
to find the created and modified time.
Something like this:
var fs = require('fs');
fs.readdir(".",function(err, list){
list.forEach(function(file){
console.log(file);
stats = fs.statSync(file);
console.log(stats.mtime);
console.log(stats.ctime);
})
})
loops the current directory (.) and logs the file name, grabs the file stats and logs the modified time (mtime) and create time (ctime)
The Brad's snippet works (and is awesome, thanks) well when the files are in the same directory, but if you are checking another folder you need to resolve the path for the statSync
param:
const fs = require('fs');
const {resolve, join} = require('path');
fs.readdir(resolve('folder/inside'),function(err, list){
list.forEach(function(file){
console.log(file);
stats = fs.statSync(resolve(join('folder/inside', file)));
console.log(stats.mtime);
console.log(stats.ctime);
})
})
I think this is a better and faster choice.
fs.readdir(".",function(err, list){
console.log(list[(list.length-1)])
})
Lets say you want to get the most recent file in a directory and send it to the client who wants to get a non-existent file in a folder. For example if your static middleware can't serve the file and automatically calls next() function.
You can use the glob module to get the list of files that you want to search, then reduce them in a function;
// handle non-existent files in a fallthrough middleware
app.use('/path_to_folder/', function (req, res) {
// search for the latest png image in the folder and send to the client
glob("./www/path_to_folder/*.png", function(err, files) {
if (!err) {
let recentFile = files.reduce((last, current) => {
let currentFileDate = new Date(fs.statSync(current).mtime);
let lastFileDate = new Date(fs.statSync(last).mtime);
return ( currentFileDate.getTime() > lastFileDate.getTime() ) ? current: last;
});
res.set("Content-Type", "image/png");
res.set("Transfer-Encoding", "chunked");
res.sendFile(path.join(__dirname, recentFile));
}
});
In order to download the latest file according to name and other stuff:
//this function runs a script
//this script exports db data
// and saves into a directory named reports
router.post("/download", function (req, res) {
//run the script
var yourscript = exec("./export.sh", (error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
});
//download latest file
function downloadLatestFile() {
//set the path
const dirPath = "/Users/tarekhabche/Desktop/awsTest/reports";
//get the latest created file
const lastFile = JSON.stringify(getMostRecentFile(dirPath));
//parse the files name since it contains a date
fileDate = lastFile.substr(14, 19);
console.log(fileDate);
//download the file
const fileToDownload = `reports/info.${fileDate}.csv`;
console.log(fileToDownload);
res.download(fileToDownload);
}
// download after exporting the db since export takes more time
setTimeout(function () {
downloadLatestFile();
}, 1000);
});
//gets the last file in a directory
const getMostRecentFile = (dir) => {
const files = orderRecentFiles(dir);
return files.length ? files[0] : undefined;
};
//orders files accroding to date of creation
const orderRecentFiles = (dir) => {
return fs
.readdirSync(dir)
.filter((file) => fs.lstatSync(path.join(dir, file)).isFile())
.map((file) => ({ file, mtime: fs.lstatSync(path.join(dir, file)).mtime }))
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
};
const dirPath = "reports";
getMostRecentFile(dirPath);