在文件夹中查找最新修改的文​​件

时间:2012-06-08 22:28:54

标签: javascript node.js

如何查看文件夹并查找哪个是最新创建/修改的文件,并将其完整路径放入var作为字符串?

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

4 个答案:

答案 0 :(得分:3)

当文件位于同一目录中时,Brad的代码段工作(并且非常棒,谢谢),但是如果要检查另一个文件夹,则需要解析statSync param的路径:

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

答案 1 :(得分:2)

查看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)

答案 2 :(得分:0)

假设您希望获取目录中的最新文件并将其发送给想要获取文件夹中不存在的文件的客户端。例如,如果您的静态中间件无法提供文件并自动调用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));
        }
    });

答案 3 :(得分:0)

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

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