purge-uploads.js 1.04 KB
Newer Older
1 2 3
/* global WIKI */

const Promise = require('bluebird')
4
const fs = require('fs-extra')
5 6 7
const moment = require('moment')
const path = require('path')

8
module.exports = async () => {
9 10 11
  WIKI.logger.info('Purging orphaned upload files...')

  try {
12
    const uplTempPath = path.resolve(process.cwd(), WIKI.config.paths.data, 'uploads')
13
    await fs.ensureDir(uplTempPath)
14
    const ls = await fs.readdir(uplTempPath)
15 16 17
    const fifteenAgo = moment().subtract(15, 'minutes')

    await Promise.map(ls, (f) => {
18
      return fs.stat(path.join(uplTempPath, f)).then((s) => { return { filename: f, stat: s } })
19 20 21
    }).filter((s) => { return s.stat.isFile() }).then((arrFiles) => {
      return Promise.map(arrFiles, (f) => {
        if (moment(f.stat.ctime).isBefore(fifteenAgo, 'minute')) {
22
          return fs.unlink(path.join(uplTempPath, f.filename))
23 24 25 26 27 28 29 30 31 32
        }
      })
    })

    WIKI.logger.info('Purging orphaned upload files: [ COMPLETED ]')
  } catch (err) {
    WIKI.logger.error('Purging orphaned upload files: [ FAILED ]')
    WIKI.logger.error(err.message)
  }
}