2

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

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

4

4 回答 4

4

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

于 2012-06-08T22:44:22.843 回答
4

当文件位于同一目录中时,Brad 的代码片段可以正常工作(并且很棒,谢谢),但是如果您正在检查另一个文件夹,则需要解析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);
    })
})
于 2017-03-05T00:56:02.387 回答
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));
        }
    });
于 2017-03-08T15:04:43.287 回答
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);
于 2021-02-05T15:28:01.723 回答