获取Node.js目录中的最新文件

Nig*_*ICU 14 node.js

我试图使用Node.js在目录中找到最近创建的文件,似乎无法找到解决方案.下面的代码似乎在一台机器上做了这个技巧,但在另一台机器上它只是从目录中拉出一个随机文件 - 正如我想的那样.基本上,我需要找到最新的文件,只需要找到该文件.

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');
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Ili*_*ski 27

假设underscore(http://underscorejs.org/)的可用性和采用同步方法(不利用node.js优势,但更容易掌握):

var fs = require('fs'),
    path = require('path'),
    _ = require('underscore');

// Return only base file name without dir
function getMostRecentFileName(dir) {
    var files = fs.readdirSync(dir);

    // use underscore for max()
    return _.max(files, function (f) {
        var fullpath = path.join(dir, f);

        // ctime = creation time is used
        // replace with mtime for modification time
        return fs.statSync(fullpath).ctime;
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 被否决是因为如果没有首先提供本机解决方案,使用第三方库解决问题被认为是不好的形式。 (4认同)

Tre*_*hek 6

虽然不是最有效的方法,但这在概念上应该是直截了当的:

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 : "";
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,原帖中没有明显的理由使用同步文件列表.


pgu*_*rio 6

另一种方法:

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
Run Code Online (Sandbox Code Playgroud)


mik*_*see 5

功能更强大的版本可能如下所示:

import { readdirSync, lstatSync } from "fs";

const orderReccentFiles = (dir: string) =>
  readdirSync(dir)
    .filter(f => lstatSync(f).isFile())
    .map(file => ({ file, mtime: lstatSync(file).mtime }))
    .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());

const getMostRecentFile = (dir: string) => {
  const files = orderReccentFiles(dir);
  return files.length ? files[0] : undefined;
};
Run Code Online (Sandbox Code Playgroud)


Tha*_*Ch. 5

首先,您需要订购文件(最新的在开头)

然后,获取最新文件的数组的第一个元素。

我修改了 @mikeysee 的代码以避免路径异常,以便我使用完整路径来修复它们。

2个函数的代码片段如下所示。

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)
Run Code Online (Sandbox Code Playgroud)


Nat*_*dly 1

不幸的是,我不认为这些文件保证按任何特定顺序排列。

相反,您需要对每个文件调用fs.stat(或fs.statSync)以获取上次修改的日期,然后在获得所有日期后选择最新的日期。