首页 > 解决方案 > 根据日期下载文件

问题描述

我有这个 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

标签: node.jsmongodb

解决方案


要做到这一点,你可以使用这个:

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);

推荐阅读