feat: use fs-jetpack in pathsController.js

This commit is contained in:
Bobby 2022-10-04 05:34:01 +07:00
parent f3bf3f6500
commit 0eb4c243c3
No known key found for this signature in database
GPG Key ID: 941839794CBF5A09
2 changed files with 10 additions and 53 deletions

View File

@ -1,31 +1,9 @@
const { promisify } = require('util')
const fs = require('fs')
const jetpack = require('fs-jetpack')
const path = require('path')
const config = require('./../config')
const logger = require('./../logger')
const self = {}
// Promisify these fs functions
const fsFuncs = [
'access',
'copyFile',
'lstat',
'mkdir',
'readdir',
'readFile',
'rename',
'rmdir',
'stat',
'symlink',
'unlink',
'writeFile'
]
for (const fsFunc of fsFuncs) {
self[fsFunc] = promisify(fs[fsFunc])
}
self.uploads = path.resolve(config.uploads.folder)
self.chunks = config.uploads.chunksFolder
? path.resolve(config.uploads.chunksFolder)
@ -47,7 +25,10 @@ self.errorRoot = path.resolve(config.errorPages.rootDir)
const verify = [
self.uploads,
self.chunks,
{
path: self.chunks,
criteria: { empty: true }
},
self.thumbs,
self.zips,
self.logs,
@ -60,34 +41,13 @@ if (['better-sqlite3', 'sqlite3'].includes(config.database.client)) {
self.initSync = () => {
// Check & create directories (synchronous)
for (const p of verify) {
try {
fs.accessSync(p)
} catch (err) {
if (err.code !== 'ENOENT') {
throw err
for (const obj of verify) {
if (typeof obj === 'object') {
jetpack.dir(obj.path, obj.criteria)
} else {
fs.mkdirSync(p)
logger.log(`Created directory: ${p}`)
jetpack.dir(obj)
}
}
}
}
self.purgeChunks = async () => {
// Purge any leftover in chunks directory
const uuidDirs = await self.readdir(self.chunks)
await Promise.all(uuidDirs.map(async uuid => {
const root = path.join(self.chunks, uuid)
const chunks = await self.readdir(root)
await Promise.all(chunks.map(chunk =>
self.unlink(path.join(root, chunk))
))
await self.rmdir(root)
}))
if (uuidDirs.length) {
logger.log(`Purged ${uuidDirs.length} unfinished chunks`)
}
}
module.exports = self

View File

@ -244,9 +244,6 @@ safe.use('/api', api)
// Init database
await require('./controllers/utils/initDatabase')(utils.db)
// Purge any leftover in chunks directory, do not wait
paths.purgeChunks()
if (!Array.isArray(config.pages) || !config.pages.length) {
logger.error('Config file does not have any frontend pages enabled')
process.exit(1)