Get the most recent file in a directory, Node.js

2020-05-25 17:37发布

I am trying to find the most recently created file in a directory using Node.js and cannot seem to find a solution. The following code seemed to be doing the trick on one machine but on another it was just pulling a random file from the directory - as I figured it might. Basically, I need to find the newest file and ONLY that file.

var fs = require('fs'); //File System
var audioFilePath = 'C:/scanner/audio/'; //Location of recorded audio files
    var audioFile = fs.readdirSync(audioFilePath)
        .slice(-1)[0]
        .replace('.wav', '.mp3');

Many thanks!

标签: node.js
11条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-05-25 17:57

Another approach:

const glob = require('glob')

const newestFile = glob.sync('input/*xlsx')
  .map(name => ({name, ctime: fs.statSync(name).ctime}))
  .sort((a, b) => b.ctime - a.ctime)[0].name
查看更多
戒情不戒烟
3楼-- · 2020-05-25 17:57

with synchronized version of read directory (fs.readdirSync) and file status (fs.statSync):

function getNewestFile(dir, regexp) {
    newest = null
    files = fs.readdirSync(dir)
    one_matched = 0

    for (i = 0; i < files.length; i++) {

        if (regexp.test(files[i]) == false)
            continue
        else if (one_matched == 0) {
            newest = files[i]
            one_matched = 1
            continue
        }

        f1_time = fs.statSync(files[i]).mtime.getTime()
        f2_time = fs.statSync(newest).mtime.getTime()
        if (f1_time > f2_time)
            newest[i] = files[i]  
    }

    if (newest != null)
        return (dir + newest)
    return null
}

you can call this function as follows:

var f = getNewestFile("./", new RegExp('.*\.mp3'))
查看更多
贼婆χ
4楼-- · 2020-05-25 18:02

this should do the trick ("dir" is the directory you use fs.readdir over to get the "files" array):

function getNewestFile(dir, files, callback) {
    if (!callback) return;
    if (!files || (files && files.length === 0)) {
        callback();
    }
    if (files.length === 1) {
        callback(files[0]);
    }
    var newest = { file: files[0] };
    var checked = 0;
    fs.stat(dir + newest.file, function(err, stats) {
        newest.mtime = stats.mtime;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            (function(file) {
                fs.stat(file, function(err, stats) {
                    ++checked;
                    if (stats.mtime.getTime() > newest.mtime.getTime()) {
                        newest = { file : file, mtime : stats.mtime };
                    }
                    if (checked == files.length) {
                        callback(newest);
                    }
                });
            })(dir + file);
        }
    });
 }
查看更多
淡お忘
5楼-- · 2020-05-25 18:04

While not the most efficient approach, this should be conceptually straight forward:

var fs = require('fs'); //File System
var audioFilePath = 'C:/scanner/audio/'; //Location of recorded audio files
fs.readdir(audioFilePath, function(err, files) {
    if (err) { throw err; }
    var audioFile = getNewestFile(files, audioFilePath).replace('.wav', '.mp3');
    //process audioFile here or pass it to a function...
    console.log(audioFile);
});

function getNewestFile(files, path) {
    var out = [];
    files.forEach(function(file) {
        var stats = fs.statSync(path + "/" +file);
        if(stats.isFile()) {
            out.push({"file":file, "mtime": stats.mtime.getTime()});
        }
    });
    out.sort(function(a,b) {
        return b.mtime - a.mtime;
    })
    return (out.length>0) ? out[0].file : "";
}

BTW, there is no obvious reason in the original post to use synchronous file listing.

查看更多
够拽才男人
6楼-- · 2020-05-25 18:06

Unfortunately, I don't think the files are guaranteed to be in any particular order.

Instead, you'll need to call fs.stat (or fs.statSync) on each file to get the date it was last modified, then select the newest one once you have all of the dates.

查看更多
做自己的国王
7楼-- · 2020-05-25 18:09

First, you need to order files (newest at the begin)

Then, get the first element of an array for the most recent file.

I have modified code from @mikeysee to avoid the path exception so that I use the full path to fix them.

The snipped codes of 2 functions are shown below.

const fs = require('fs');
const path = require('path');

const getMostRecentFile = (dir) => {
    const files = orderReccentFiles(dir);
    return files.length ? files[0] : undefined;
};

const orderReccentFiles = (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 = '<PATH>';
getMostRecentFile(dirPath)
查看更多
登录 后发表回答