简体   繁体   English

获取文件夹中的最新文件

[英]Get latest files inside a folder

i have a folder stucture like我有一个文件夹结构像

var/ 
    testfolder1/
                myfile.rb
                data.rb
    testfolder2/ 
               home.rb
                sub.rb
    sample.rb
    rute.rb

inside var folder contains subfolders(testfolder1,testfolder2) and some files(sample.rb,rute.rb) in the following code returing a josn object that contains folders and files inside the var folder like var 文件夹内包含子文件夹(testfolder1,testfolder2)和以下代码中的一些文件(sample.rb,rute.rb),返回一个 josn 对象,其中包含 var 文件夹中的文件夹和文件,如

{
    '0': ['sample.rb', 'rute.rb'],
    testfolder1: ['myfile.rb',
        'data.rb',
    ],
    testfolder2: ['home.rb',
        'sub.rb',
    ]

}

code代码

 var scriptsWithGroup = {};
    fs.readdir('/home/var/', function(err, subfolder) {
      if(err) return context.sendJson({}, 200);
      var scripts = [];
      for (var j = 0; j < subfolder.length; j++) {
        var scriptsInFolder = [];
        if(fs.lstatSync(scriptPath + subfolder[j]).isDirectory()) {
          fs.readdirSync(scriptPath + subfolder[j]).forEach(function(file) { 
            if (file.substr(file.length - 3) == '.rb')
            scriptsInFolder.push(file);
          });
          scriptsWithGroup[subfolder[j]] = scriptsInFolder;
        } else {
          if (subfolder[j].substr(subfolder[j].length - 3) == '.rb')
            scripts.push(subfolder[j]);
        }
      }
      scriptsWithGroup["0"] = scripts;

console.log(scriptsWithGroup)
      context.sendJson(scriptsWithGroup, 200);
    });

What i need is i want to return the latest modified or created files.here i only use 2 files inside folders it contains lots of files.so i want to return latest created ones我需要的是我想返回最新修改或创建的文件。这里我只使用文件夹中的 2 个文件,它包含很多文件。所以我想返回最新创建的文件

I'm going to assume here that you want only the most recent two files.我将在这里假设您需要最近的两个文件。 If you actually want them all, just sorted, just remove the slice portion of this:如果你真的想要它们,只是排序,只需删除slice部分:

scriptsInFolder = scriptsInFolder.sort(function(a, b) {
  // or mtime, if you're only wanting file changes and not file attribute changes
  var time1 = fs.statSync(a).ctime; 
  var time2 = fs.statSync(b).ctime;
  if (time1 < time2) return -1;
  if (time1 > time2) return 1;
  return 0;
}).slice(0, 2);

I'll add, however, that it's typically considered best practice not to use to the synchronize fs methods (eg fs.statSync ).但是,我要补充一点,通常认为最好的做法是不使用同步 fs 方法(例如fs.statSync )。 If you're able to install async , that would be a good alternative approach.如果您能够安装async ,那将是一个很好的替代方法。

const fs = require('fs');
const path = require('path');

const getMostRecentFile = (dir) => {
    const files = orderReccentFiles(dir);
    return files.length ? files[0] : undefined;
};

const orderReccentFiles = (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 = '<PATH>';
console.log(getMostRecentFile(dirPath));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM