Merge pull request #24 from mike-marcacci/stream-comments

Update the handling of streams and add comments.
This commit is contained in:
Jayden Seric 2019-12-22 12:15:18 +11:00 committed by GitHub
commit 4e222c046c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -31,15 +31,27 @@ const storeUpload = async upload => {
// Store the file in the filesystem.
await new Promise((resolve, reject) => {
stream
.on('error', error => {
unlink(path, () => {
reject(error)
})
// Create a stream to which the upload will be written.
const writeStream = createWriteStream(path)
// When the upload is fully written, resolve the promise.
writeStream.on('finish', resolve)
// If there's an error writing the file, remove the partially written file
// and reject the promise.
writeStream.on('error', error => {
unlink(path, () => {
reject(error)
})
.pipe(createWriteStream(path))
.on('error', reject)
.on('finish', resolve)
})
// In node <= 13, errors are not automatically propagated between piped
// streams. If there is an error receiving the upload, destroy the write
// stream with the corresponding error.
stream.on('error', error => writeStream.destroy(error))
// Pipe the upload into the write stream.
stream.pipe(writeStream)
})
// Record the file metadata in the DB.