Reputation: 11
I need to know how can i mention "filter" the files per date for example files of day: 2 until 12.
const fs = require('fs'); const testFolder = 'C:/Users/duff/Downloads/xmlpath/'; fs.readdirSync(testFolder).forEach(file => { //Reading files from folder fs.stat(testFolder+file,'utf8', function(err,data){ console.log(data.mtime); // print the last modified date } ); });
I've tried with this code but i get all files dates without filtering them
Upvotes: 0
Views: 1831
Reputation: 11
This is how with some additional stuff where i am saving files and retrieving the final file :
router.post("/download", function (req, res) {
var yourscript = exec("./export.sh", (error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
});
function downloadLatestFile() {
const dirPath = "/Users/tarekhabche/Desktop/awsTest/reports";
const lastFile = JSON.stringify(getMostRecentFile(dirPath));
fileDate = lastFile.substr(14, 19);
console.log(fileDate);
const fileToDownload = `reports/info.${fileDate}.csv`;
console.log(fileToDownload);
res.download(fileToDownload);
}
setTimeout(function () {
downloadLatestFile();
}, 1000);
});
const getMostRecentFile = (dir) => {
const files = orderRecentFiles(dir);
return files.length ? files[0] : undefined;
};
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);
Upvotes: 0
Reputation: 1229
So I think what you want to do is provide a date range and return the files within that range.
I'm stripping the hours and making comparison against the dates here
const fs = require('fs')
const testFolder = './test'
const parseDate = timestamp => new Date(timestamp).toISOString().slice(0, 10)
const handler = async (f, t) => {
const startDate = parseDate(f)
const endDate = parseDate(t)
const timestamp = file => {
return new Promise((resolve, reject) => {
fs.stat(`${testFolder}/${file}`, 'utf8', (err, data) => {
if (err) return reject(err)
return resolve({ filename: `${testFolder}/${file}`, date: parseDate(data.mtime) })
})
})
}
const timestamps = await Promise.all(fs.readdirSync(testFolder).map(timestamp))
return timestamps.filter(({ date }) => date >= startDate && date <= endDate)
}
handler('2020-04-01', '2020-04-10')
This will then produce an array of objects like so
[ { filename: 'C:/Users/duff/Downloads/xmlpath/test1', date: '2020-04-09' },
{ filename: 'C:/Users/duff/Downloads/xmlpath/hello', date: '2020-04-09' },
{ filename: 'C:/Users/duff/Downloads/xmlpath/new', date: '2020-04-10' },
{ filename: 'C:/Users/duff/Downloads/xmlpath/yes', date: '2020-04-10' } ]
Upvotes: 0