Skip to content

Commit

Permalink
支持删除过期文件
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Aug 18, 2020
1 parent 2c29a28 commit b10e6d0
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as colors from 'colors/safe'
import * as express from 'express'
// eslint-disable-next-line no-duplicate-imports
import {NextFunction, Request, Response} from 'express'
import {outputFile, pathExists} from 'fs-extra'
import {outputFile, pathExists, readdir, stat, unlink} from 'fs-extra'
import got, {Got} from 'got'
import {createServer, Server} from 'http'
import {join} from 'path'
Expand Down Expand Up @@ -97,6 +97,7 @@ export class Cluster {
})
await outputFile(path, res.body)
}
await this.gc(fileList)
}

public setupExpress(): Server {
Expand Down Expand Up @@ -181,7 +182,7 @@ export class Cluster {
searchParams: {noopen: 1},
})

const path = join(this.cacheDir, hash.substr(0, 2), hash)
const path = join(this.cacheDir, this.hashToFilename(hash))
await outputFile(path, res.body)
}

Expand Down Expand Up @@ -254,4 +255,32 @@ export class Cluster {
process.exit(1)
}
}

private async gc(fileList: IFileList): Promise<void> {
const fileSet = new Set<string>()
for (const file of fileList.files) {
fileSet.add(`/${this.hashToFilename(file.hash)}`)
}
const queue = [this.cacheDir]
do {
const dir = queue.pop()
const entries = await readdir(dir)
for (const entry of entries) {
const p = join(dir, entry)
const s = await stat(p)
if (s.isDirectory()) {
queue.push(p)
continue
}
if (!fileSet.has(p.replace(this.cacheDir, ''))) {
console.log(colors.gray(`delete expire file: ${p}`))
await unlink(p)
}
}
} while (queue.length !== 0)
}

private hashToFilename(hash: string): string {
return join(hash.substr(0, 2), hash)
}
}

0 comments on commit b10e6d0

Please sign in to comment.