te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Finding latest modified file in a folder - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Finding latest modified file in a folder - Stack Overflow

programmeradmin4浏览0评论

How do I go through a folder and find out which is the newest created/modified file and put the full path of it into a var as string?

Haven't really figured out io/best practices for io

How do I go through a folder and find out which is the newest created/modified file and put the full path of it into a var as string?

Haven't really figured out io/best practices for io

Share Improve this question asked Jun 8, 2012 at 22:28 jmoonjmoon 5763 gold badges7 silver badges18 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

Take a look at http://nodejs/api/fs.html#fs_class_fs_stats

look at the ctime or mtime to find the created and modified time.

Something like this:

var fs = require('fs');

fs.readdir(".",function(err, list){
    list.forEach(function(file){
        console.log(file);
        stats = fs.statSync(file);
        console.log(stats.mtime);
        console.log(stats.ctime);
    })
})

loops the current directory (.) and logs the file name, grabs the file stats and logs the modified time (mtime) and create time (ctime)

The Brad's snippet works (and is awesome, thanks) well when the files are in the same directory, but if you are checking another folder you need to resolve the path for the statSync param:

const fs = require('fs');
const {resolve, join} = require('path');

fs.readdir(resolve('folder/inside'),function(err, list){
    list.forEach(function(file){
       console.log(file);
       stats = fs.statSync(resolve(join('folder/inside', file)));
       console.log(stats.mtime);
       console.log(stats.ctime);
    })
})

I think this is a better and faster choice.

fs.readdir(".",function(err, list){
    console.log(list[(list.length-1)])
})

Lets say you want to get the most recent file in a directory and send it to the client who wants to get a non-existent file in a folder. For example if your static middleware can't serve the file and automatically calls next() function.

You can use the glob module to get the list of files that you want to search, then reduce them in a function;

// handle non-existent files in a fallthrough middleware
app.use('/path_to_folder/', function (req, res) {
    // search for the latest png image in the folder and send to the client
    glob("./www/path_to_folder/*.png", function(err, files) {
        if (!err) {

            let recentFile = files.reduce((last, current) => {

                let currentFileDate = new Date(fs.statSync(current).mtime);
                let lastFileDate = new Date(fs.statSync(last).mtime);

                return ( currentFileDate.getTime() > lastFileDate.getTime() ) ? current: last;
            });

            res.set("Content-Type", "image/png");
            res.set("Transfer-Encoding", "chunked");
            res.sendFile(path.join(__dirname, recentFile));
        }
    });

In order to download the latest file according to name and other stuff:

//this function runs a script
//this script exports db data
// and saves into a directory named reports
router.post("/download", function (req, res) {

//run the script
  var yourscript = exec("./export.sh", (error, stdout, stderr) => {
    console.log(stdout);
    console.log(stderr);
  });
//download latest file
  function downloadLatestFile() {
//set the path
    const dirPath = "/Users/tarekhabche/Desktop/awsTest/reports";
//get the latest created file
    const lastFile = JSON.stringify(getMostRecentFile(dirPath));
//parse the files name since it contains a date

    fileDate = lastFile.substr(14, 19);
    console.log(fileDate);
//download the file
    const fileToDownload = `reports/info.${fileDate}.csv`;
    console.log(fileToDownload);
    res.download(fileToDownload);
  }
// download after exporting the db since export takes more time
  setTimeout(function () {
    downloadLatestFile();
  }, 1000);
});
//gets the last file in a directory

const getMostRecentFile = (dir) => {
  const files = orderRecentFiles(dir);
  return files.length ? files[0] : undefined;
};
//orders files accroding to date of creation
const orderRecentFiles = (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 = "reports";
getMostRecentFile(dirPath);
发布评论

评论列表(0)

  1. 暂无评论