node.js - 根据日期下载文件
问题描述
我有这个 shell 脚本:
#while true; do
#sleep 600
echo "####Removing then Rebuilding###"
today=`date +%Y-%m-%dT%H:%M:%S`
cd reports
mongoexport --db=graphqlAmazonV2 --collection=purchasefromappobjectmodels --type=csv --fields=_id,receiptId,sku,itemType,UserData,purchaseDate,idfa,status --out=info.$today.csv
#done
如图所示,它从数据库中导出数据并保存为 .csv 文件。我添加了$today
日期,以便我知道 csv 文件是何时创建的。在此之前,我有一个 csvinfo.csv
文件被删除然后再次导出,因此我可以使用 express 内置文件下载器轻松下载。
const file = `${__dirname}/reports/info.csv`;
console.log("downloading ... ");
res.download(file);
现在该文件没有固定的名称,它会根据其初始化日期进行更改和命名。
例子 :info.2021-02-04T20:10:02.csv
我现在怎么下载?我想解析文件名并与现在的日期进行比较然后下载。
第2步:根据过滤器下载This question i will post later
解决方案
要做到这一点,你可以使用这个:
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);
推荐阅读
- regex - 正则表达式 - 删除模式前面的空格
- python - 将 Pyomo 导出到 .mps 文件时保留变量名
- javascript - 当元素(div)在Angular中可见和不可见时使用回调?
- c# - ASP.NET Core 3.1:查询字符串参数确定正文的类
- xcode - 导入到新机器后,Xcode 档案被识别为 macOS 应用程序而不是 iOS
- typescript - 如何在打字稿中扩展记录类型的键
- javascript - 从 Github 复制 CSV 链接并将其与导致错误的绘图代码结合起来
- arduino - 将字符串反序列化为 StaticJsonDocument
- javascript - 放入elementor modal弹出框显示“订阅确认”
- python - 熊猫条形图结合折线图显示了从 1970 年开始的时间轴