await-mtime-parallel.js 1.03 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)}`)
})