gancio-upstream/server/api/storage.js

66 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-04-03 00:25:12 +02:00
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const mkdirp = require('mkdirp')
const sharp = require('sharp')
const debug = require('debug')('storage')
const config = require('config')
2019-04-03 00:25:12 +02:00
2019-07-03 16:58:24 +02:00
try {
mkdirp.sync(config.upload_path + '/thumb')
} catch (e) {
debug.warn(e)
2019-07-03 16:58:24 +02:00
}
2019-04-03 00:25:12 +02:00
const DiskStorage = {
2019-09-11 19:12:24 +02:00
_handleFile (req, file, cb) {
2020-07-08 23:02:08 +02:00
const filename = crypto.randomBytes(16).toString('hex') + '.jpg'
const finalPath = path.resolve(config.upload_path, filename)
const thumbPath = path.resolve(config.upload_path, 'thumb', filename)
2019-04-03 00:25:12 +02:00
const outStream = fs.createWriteStream(finalPath)
const thumbStream = fs.createWriteStream(thumbPath)
2020-07-08 23:02:08 +02:00
const resizer = sharp().resize(1200).jpeg({ quality: 95 })
const thumbnailer = sharp().resize(400).jpeg({ quality: 90 })
let onError = false
const err = e => {
if (onError) {
return
}
onError = true
debug(e)
req.err = e
cb(null)
}
file.stream
.pipe(thumbnailer)
.on('error', err)
.pipe(thumbStream)
.on('error', err)
file.stream
.pipe(resizer)
.on('error', err)
.pipe(outStream)
.on('error', err)
2019-04-03 00:25:12 +02:00
outStream.on('finish', () => {
2019-04-03 00:25:12 +02:00
cb(null, {
destination: config.upload_path,
2019-04-03 00:25:12 +02:00
filename,
path: finalPath,
size: outStream.bytesWritten
})
})
},
2019-09-11 19:12:24 +02:00
_removeFile (req, file, cb) {
delete file.destination
delete file.filename
fs.unlink(file.path, cb)
delete file.path
}
2019-04-03 00:25:12 +02:00
}
module.exports = DiskStorage