【问题标题】:How to filter files from the Last modified date如何从上次修改日期过滤文件
【发布时间】:2020-07-21 15:54:44
【问题描述】:

我需要知道如何按日期“过滤”文件,例如当天的文件:2 到 12。

常量 fs = 要求('fs'); const testFolder = 'C:/Users/duff/Downloads/xmlpath/'; fs.readdirSync(testFolder).forEach(file => { //从文件夹中读取文件 fs.stat(testFolder+file,'utf8', function(err,data){ 控制台.log(data.mtime); // 打印最后修改日期 } ); });

我已尝试使用此代码,但我得到了所有文件的日期而没有过滤它们

result of files dates

【问题讨论】:

  • 您可以考虑使用 Moment.js 将屏幕截图中的时间戳转换为 Unix timestamps,这是自 1970 年 1 月 1 日以来以毫秒为单位的纯数值。这可能会使排序更容易。

标签: node.js


【解决方案1】:

所以我认为你想要做的是提供一个日期范围并返回该范围内的文件。

我正在剥离时间并与此处的日期进行比较

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

这将产生一个像这样的对象数组

[ { 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' } ]

【讨论】:

  • 谢谢你!真的很有帮助,我在这里感到沮丧。但我在这里尝试比较相同的日期,例如:handler('2020-04-11', '2020-04-11') 和结果所有数组范围。我做错了什么? @razki
  • 没问题!啊,你想要时间而不是日期? - 抱歉,如果是这样的话,我一定是误读了你的问题
  • 不,这正是我们想要做的。你的方法真好。现在,当我将同一天的日期设置为“2020-04-11”时,该数组也会返回该日期的过去文件,例如“2020-04-10”、“2020-04-09”和“2020-04-” 08'.---> Image – 漫步佩雷拉·达席尔瓦
【解决方案2】:

这就是我保存文件和检索最终文件的一些附加内容的方式:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 2020-03-27
    • 2021-04-25
    • 2021-10-08
    • 2017-01-02
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多