需要从特定目录中读取文件列表,其中日期按降序或升序修改Node js.
我已经尝试过下面的代码但无法得到解决方案。
fs.readdir(path, function (err, files) {
if (err) throw err;
else {
var res = [];
files.forEach(function (file) {
if (file.split('.')[1] == "json") {
fs.stat(path, function (err, stats) {
});
res.push(file.substring(0, file.length - 5));
}
});
}
stats 参数给出 mtime 作为修改时间?
有没有办法获取带有修改日期的文件。
mtime
给出 Unix 时间戳。您可以轻松转换为日期,
const date = new Date(mtime);
对于您的排序问题,您可以执行以下操作
var dir = 'mydir/';
fs.readdir(dir, function(err, files){
files = files.map(function (fileName) {
return {
name: fileName,
time: fs.statSync(dir + '/' + fileName).mtime.getTime()
};
})
.sort(function (a, b) {
return a.time - b.time; })
.map(function (v) {
return v.name; });
});
files
将是一个按升序排列的文件数组。
对于下降,只需替换a.time
with b.time
, like b.time - a.time
更新:ES6+版本
const myDir = 'mydir';
const getSortedFiles = async (dir) => {
const files = await fs.promises.readdir(dir);
return files
.map(fileName => ({
name: fileName,
time: fs.statSync(`${dir}/${fileName}`).mtime.getTime(),
}))
.sort((a, b) => a.time - b.time)
.map(file => file.name);
};
getSortedFiles(myDir)
.then(console.log)
.catch(console.error);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)