Add comments to stream example

This commit is contained in:
Mike Marcacci 2019-12-21 13:31:58 -05:00
parent 563e66cb7b
commit b0b1a72ce7

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.