From b0b1a72ce76112725e6ac9f2e218c9a8c40ade79 Mon Sep 17 00:00:00 2001 From: Mike Marcacci Date: Sat, 21 Dec 2019 13:31:58 -0500 Subject: [PATCH] Add comments to stream example --- api/server.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/api/server.js b/api/server.js index a745012..658a731 100644 --- a/api/server.js +++ b/api/server.js @@ -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.