Get the most recent file in a directory, Node.js
node.js
Solution
Assuming availability of `underscore` (http://underscorejs.org/) and taking synchronous approach (which doesn't utilize the node.js strengths, but is easier to grasp):
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;
});
}
Problem
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!