const fs = require('fs').promises
// Returns a Promise<number> that computes the most recent
// modification time for any file inside a directory
async function modifiedTime(path) {
// First, we wait for the fs.stat() Promise
const stats = await fs.stat(path)
const {mtimeMs} = stats
// If this path is a file, return its modification time
if (!stats.isDirectory()) return mtimeMs
// If this is a directory, check all files inside for later modified times
// Get a list of all files/subdirectories in the directory
const files = await fs.readdir(path)
// Then get the modified time of each file/subdirectory in parallel
const modifiedTimes = await Promise.all(files.map(file =>
modifiedTime(path + '/' + file)
))
// Return the latest modification time
return Math.max(mtimeMs, ...modifiedTimes)
}
// Even though we return a number from modifiedTime, the number
// is wrapped in a Promise because it is an async function
modifiedTime('.').then(mTime => {
console.log(`Most recent modification: ${new Date(mTime)}`)
})
-
Caleb C. Sander authoredecfb12b9