recursive-mtime.js 1.08 KB
Newer Older
Caleb C. Sander's avatar
Caleb C. Sander committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const fs = require('fs').promises

// Returns a Promise<number> that computes the most recent
// modification time for any file inside a directory
const modifiedTime = path =>
  fs.stat(path).then(stats => {
    // mtimeMs is the modification time for this file/directory
    const {mtimeMs} = stats
    if (stats.isDirectory()) {
      // If this is a directory, compute the modification time
      // for all files/subdirectories inside it
      return fs.readdir(path)
        .then(files =>
          // Compute modification times of all contained files
          Promise.all(files.map(file =>
            modifiedTime(path + '/' + file)
          ))
        )
        // modifiedTimes will be an array containing the latest
        // modification time of each file in the directory
21
22
23
        .then(modifiedTimes =>
          Promise.resolve(Math.max(mtimeMs, ...modifiedTimes))
        )
Caleb C. Sander's avatar
Caleb C. Sander committed
24
25
26
27
28
29
30
31
    }
    // If this is a file, just return its modification time
    else return Promise.resolve(mtimeMs)
  })

modifiedTime('.').then(mTime => {
  console.log(`Most recent modification: ${new Date(mTime)}`)
})