Javascript 使用 Node.JS,如何获取按时间顺序排列的文件列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10559685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Node.JS, how do you get a list of files in chronological order?
提问by Newtang
For a given directory, how can I get a list of files in chronological order (by date-modified) in Node.JS? I didn't see anything in the File System docs.
对于给定的目录,如何在 Node.JS 中按时间顺序(按修改日期)获取文件列表?我在文件系统文档中没有看到任何内容。
回答by cliffs of insanity
Give this a shot.
试一试。
var dir = './'; // your directory
var files = fs.readdirSync(dir);
files.sort(function(a, b) {
return fs.statSync(dir + a).mtime.getTime() -
fs.statSync(dir + b).mtime.getTime();
});
I used the "sync" version of the methods. You should make them asynchronous as needed. (Probably just the readdir
part.)
我使用了这些方法的“同步”版本。您应该根据需要使它们异步。(可能只是readdir
一部分。)
You can probably improve performance a bit if you cache the stat info.
如果您缓存统计信息,您可能会稍微提高性能。
var files = fs.readdirSync(dir)
.map(function(v) {
return { name:v,
time:fs.statSync(dir + v).mtime.getTime()
};
})
.sort(function(a, b) { return a.time - b.time; })
.map(function(v) { return v.name; });
回答by Krzysztof Rosiński
Async version (2018)
异步版本 (2018)
const fs = require('fs');
const path = require('path');
const util = require('util');
const readdirAsync = util.promisify(fs.readdir);
const statAsync = util.promisify(fs.stat);
async function readdirChronoSorted(dirpath, order) {
order = order || 1;
const files = await readdirAsync(dirpath);
const stats = await Promise.all(
files.map((filename) =>
statAsync(path.join(dirpath, filename))
.then((stat) => ({ filename, stat }))
)
);
return stats.sort((a, b) =>
order * (b.stat.mtime.getTime() - a.stat.mtime.getTime())
).map((stat) => stat.filename);
}
(async () => {
try {
const dirpath = path.join(__dirname);
console.log(await readdirChronoSorted(dirpath));
console.log(await readdirChronoSorted(dirpath, -1));
} catch (err) {
console.log(err);
}
})();
回答by Ismael Martinez
I ended up using underscore as gives the opportunity to account for what stat to use for the sorting.
我最终使用下划线,因为有机会说明用于排序的统计数据。
1st get the files in the directory using files = fs.readFileSync(directory);
(you might want to try catch err in case directory does not exist or read permissions)
1st 获取目录中的文件使用files = fs.readFileSync(directory);
(如果目录不存在或读取权限,您可能想尝试 catch err)
Then pass them to a function like the following one. That will return you the ordered list.
然后将它们传递给如下所示的函数。这将返回有序列表。
function orderByCTime(directory, files) {
var filesWithStats = [];
_.each(files, function getFileStats(file) {
var fileStats = fs.statSync(directory + file);
filesWithStats.push({
filename: file,
ctime: fileStats.ctime
});
file = null;
});
return _.sortBy(filesWithStats, 'ctime').reverse();
}
Underscore sort by asc by default. I reverse it as I need it descending order.
下划线默认按 asc 排序。我将其反转,因为我需要它以降序排列。
You could decide to sort by another stat (check node fs documentation here). I choose to use ctime as it should account for "touching" the file also.
您可以决定按另一个统计信息排序(在此处查看节点 fs 文档)。我选择使用 ctime,因为它也应该考虑“触摸”文件。
Hope helps,
希望有所帮助,