【问题标题】:Finding latest modified file in a folder在文件夹中查找最新修改的文​​件
【发布时间】:2012-06-12 23:29:42
【问题描述】:

如何浏览文件夹并找出最新创建/修改的文件并将其完整路径作为字符串放入 var 中?

还没有真正弄清楚 io/io 的最佳实践

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    看看http://nodejs.org/api/fs.html#fs_class_fs_stats

    查看ctimemtime 以查找创建和修改时间。

    类似这样的:

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

    循环当前目录(.)并记录文件名,抓取文件统计信息并记录修改时间(mtime)和创建时间(ctime)

    【讨论】:

    • 如果我有 700 个文件,我的情况就是这样。
    【解决方案2】:

    当文件位于同一目录中时,Brad 的 sn-p 可以正常工作(非常棒,谢谢),但如果您正在检查另一个文件夹,则需要解析 statSync 参数的路径:

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

    【讨论】:

      【解决方案3】:

      假设您想要获取目录中的最新文件并将其发送给想要获取文件夹中不存在的文件的客户端。例如,如果您的静态中间件无法提供文件并自动调用 next() 函数。

      您可以使用 glob 模块获取您要搜索的文件列表,然后在一个函数中对它们进行归约;

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

      【讨论】:

        【解决方案4】:

        为了根据名称和其他东西下载最新的文件:

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

        【讨论】:

        • 如果对您的代码有更多解释,了解它如何准确解决问题,我会很有用。
        • @BenjaminZach 会做的
        • @BenjaminZach 更好?如果您可以投票,因为我无法提出任何问题
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 2019-07-08
        • 1970-01-01
        • 2019-12-22
        相关资源
        最近更新 更多