hotfix handle error on multer streaming

This commit is contained in:
les
2020-01-15 23:52:28 +01:00
parent a444bd42f7
commit 1980c51ec3

View File

@@ -3,30 +3,48 @@ const path = require('path')
const crypto = require('crypto') const crypto = require('crypto')
const mkdirp = require('mkdirp') const mkdirp = require('mkdirp')
const sharp = require('sharp') const sharp = require('sharp')
const consola = require('consola') const debug = require('debug')('storage')
const config = require('config') const config = require('config')
try { try {
mkdirp.sync(config.upload_path + '/thumb') mkdirp.sync(config.upload_path + '/thumb')
} catch (e) { } catch (e) {
consola.error(e) debug.warn(e)
} }
const DiskStorage = { const DiskStorage = {
_handleFile (req, file, cb) { _handleFile (req, file, cb) {
const filename = crypto.randomBytes(16).toString('hex') + '.jpg' const filename = crypto.randomBytes(16).toString('hex') + '.webp'
const finalPath = path.resolve(config.upload_path, filename) const finalPath = path.resolve(config.upload_path, filename)
const thumbPath = path.resolve(config.upload_path, 'thumb', filename) const thumbPath = path.resolve(config.upload_path, 'thumb', filename)
const outStream = fs.createWriteStream(finalPath) const outStream = fs.createWriteStream(finalPath)
const thumbStream = fs.createWriteStream(thumbPath) const thumbStream = fs.createWriteStream(thumbPath)
const resizer = sharp().resize(1200).jpeg({ quality: 95 })
const thumbnailer = sharp().resize(400).jpeg({ quality: 90 })
file.stream.pipe(thumbnailer).pipe(thumbStream) const resizer = sharp().resize(1200).webp({ quality: 95 })
thumbStream.on('error', e => consola.error('thumbStream error ', e)) const thumbnailer = sharp().resize(400).webp({ 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)
file.stream.pipe(resizer).pipe(outStream)
outStream.on('error', cb)
outStream.on('finish', function () { outStream.on('finish', function () {
cb(null, { cb(null, {
destination: config.upload_path, destination: config.upload_path,
@@ -39,8 +57,8 @@ const DiskStorage = {
_removeFile (req, file, cb) { _removeFile (req, file, cb) {
delete file.destination delete file.destination
delete file.filename delete file.filename
fs.unlink(file.path, cb)
delete file.path delete file.path
fs.unlink(path, cb)
} }
} }