我正在尝试使用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');
非常感谢!
答案 0 :(得分:23)
假设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;
});
}
答案 1 :(得分: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 : "";
}
BTW,原帖中没有明显的理由使用同步文件列表。
答案 2 :(得分:3)
这应该可以解决问题(" dir"是使用fs.readdir来获取"文件"数组的目录):
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);
}
});
}
答案 3 :(得分:3)
首先,您需要订购文件(开头是最新的)
然后,获取最新文件的数组的第一个元素。
我已经修改了@mikeysee中的代码,以避免出现路径异常,以便使用完整路径修复它们。
两个功能的代码如下所示。
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)
答案 4 :(得分:2)
不幸的是,我认为文件不保证按任何特定顺序排列。
相反,您需要在每个文件上调用fs.stat(或fs.statSync)以获取上次修改的日期,然后在获得所有日期后选择最新的日期。< / p>
答案 5 :(得分:2)
[扩展umair的答案,以纠正当前工作目录的错误]
sh: 1: /home/Documents/OMP/bin/Debug/OMP: not found
答案 6 :(得分:2)
另一种方法:
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
答案 7 :(得分:1)
具有读取目录的同步版本(fs.readdirSync)和文件状态(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
}
您可以按如下方式调用此函数:
var f = getNewestFile("./", new RegExp('.*\.mp3'))
答案 8 :(得分:1)
使用纯JavaScript和易于理解的结构:
function getLatestFile(dirpath) {
// Check if dirpath exist or not right here
let latest;
const files = fs.readdirSync(dirpath);
files.forEach(filename => {
// Get the stat
const stat = fs.lstatSync(path.join(dirpath, filename));
// Pass if it is a directory
if (stat.isDirectory())
return;
// latest default to first file
if (!latest) {
latest = {filename, mtime: stat.mtime};
return;
}
// update latest if mtime is greater than the current latest
if (stat.mtime > latest.mtime) {
latest.filename = filename;
latest.mtime = stat.mtime;
}
});
return latest.filename;
}
答案 9 :(得分:1)
更具功能性的版本可能如下:
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;
};
答案 10 :(得分:0)
令人惊讶的是,此问题中没有明确使用数组函数,函数式编程的示例。
这是我在nodejs中获取目录的最新文件的看法。默认情况下,它将通过任何扩展名获取最新文件。传递扩展属性时,该函数将返回该扩展名的最新文件。
这段代码的优点在于它的声明性和模块性,易于理解,反对使用&#34;逻辑分支/控制流&#34;当然,只要你了解这些数组函数是如何工作的
const fs = require('fs');
const path = require('path');
function getLatestFile({directory, extension}, callback){
fs.readdir(directory, (_ , dirlist)=>{
const latest = dirlist.map(_path => ({stat:fs.lstatSync(path.join(directory, _path)), dir:_path}))
.filter(_path => _path.stat.isFile())
.filter(_path => extension ? _path.dir.endsWith(`.${extension}`) : 1)
.sort((a, b) => b.stat.mtime - a.stat.mtime)
.map(_path => _path.dir);
callback(latest[0]);
});
}
getLatestFile({directory:process.cwd(), extension:'mp3'}, (filename=null)=>{
console.log(filename);
});
&#13;