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!
Another approach:
with synchronized version of read directory (fs.readdirSync) and file status (fs.statSync):
you can call this function as follows:
this should do the trick ("dir" is the directory you use fs.readdir over to get the "files" array):
While not the most efficient approach, this should be conceptually straight forward:
BTW, there is no obvious reason in the original post to use synchronous file listing.
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.
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.