Skip to content

Commit

Permalink
fix(vfs): defer vfs cleanup
Browse files Browse the repository at this point in the history
Defers the VFS cleanup process and slightly cleans up the error
handling in the request chain to prevent crashing when streams
are destroyed by the runtime.

Fixes #79
  • Loading branch information
andersevenrud committed Jan 2, 2024
1 parent f1c684a commit ed0686d
Showing 1 changed file with 17 additions and 20 deletions.
37 changes: 17 additions & 20 deletions src/vfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,16 @@ const parseRangeHeader = (range, size) => {
const onDone = (req, res) => {
if (req.files) {
for (let fieldname in req.files) {
try {
fs.removeSync(req.files[fieldname].path);
} catch (e) {
console.warn('Failed to unlink temporary file', e);
}
const n = req.files[fieldname].path;
setImmediate(() => {
try {
if (fs.existsSync(n)) {
fs.removeSync(n);
}
} catch (e) {
console.warn('Failed to unlink temporary file', e);
}
});
}
}
};
Expand All @@ -77,26 +82,18 @@ const onDone = (req, res) => {
* Wraps a vfs adapter request
*/
const wrapper = fn => (req, res, next) => fn(req, res)
.then(result => {
.then(result => new Promise((resolve, reject) => {
if (result instanceof Stream) {
result.on('error', error => {
next(error);
});

result.on('end', () => {
onDone(req, res);
});

result.once('error', reject);
result.once('end', resolve);
result.pipe(res);
} else {
res.json(result);
onDone(req, res);
resolve();
}
})
.catch(error => {
next(error);
onDone(req, res);
});
}))
.catch(error => next(error))
.finally(() => onDone(req, res));

/**
* Creates the middleware
Expand Down

0 comments on commit ed0686d

Please sign in to comment.