使用Node.JS,如何按时间顺序获取文件列表? [英] Using Node.JS, how do you get a list of files in chronological order?

查看:1358
本文介绍了使用Node.JS,如何按时间顺序获取文件列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的目录,如何在Node.JS中按时间顺序(按日期修改)获取文件列表?我没有在文件系统文档中看到任何东西。

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.

推荐答案

给这个镜头。

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();
           });

我使用了同步版本的方法。您应该根据需要使其异步。 (可能只是 readdir 部分。)

I used the "sync" version of the methods. You should make them asynchronous as needed. (Probably just the readdir part.)

你可以如果缓存统计信息,可以提高性能。

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; });

这篇关于使用Node.JS,如何按时间顺序获取文件列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆