1.首先安装这个库

https://www.npmjs.com/package/recursive-readdir

2.代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const util = require("util");
const recursive = require("recursive-readdir");
const readdirAsync = util.promisify(recursive);
const statAsync = util.promisify(fs.stat);

const files = await readdirAsync(basepath);
const stats = await Promise.all(
  files.map((filename) =>
    statAsync(filename).then((stat) => ({
      filename,
      stat,
    }))
  )
);
const sortedFiles = stats
  .sort((a, b) => a.stat.mtime.getTime() - b.stat.mtime.getTime())
  .map((stat) => stat.filename);

console.log(sortedFiles);