Skip to content

Commit

Permalink
Add empty files support for tempFileHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
RomanBurunkov committed Jul 16, 2020
1 parent b24233d commit d8c00c5
Showing 1 changed file with 14 additions and 24 deletions.
38 changes: 14 additions & 24 deletions lib/tempFileHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,23 @@ module.exports = (options, fieldname, filename) => {
const hash = crypto.createHash('md5');
let fileSize = 0;
let completed = false;

let writeStream = false;
let writePromise = Promise.resolve();

const createWriteStream = () => {
debugLog(options, `Opening write stream for ${fieldname}->${filename}...`);
writeStream = fs.createWriteStream(tempFilePath);
writePromise = new Promise((resolve, reject) => {
writeStream.on('finish', () => {
resolve();
});
writeStream.on('error', (err) => {
debugLog(options, `Error write temp file: ${err}`);
reject(err);
});
debugLog(options, `Opening write stream for ${fieldname}->${filename}...`);
const writeStream = fs.createWriteStream(tempFilePath);
const writePromise = new Promise((resolve, reject) => {
writeStream.on('finish', () => resolve());
writeStream.on('error', (err) => {
debugLog(options, `Error write temp file: ${err}`);
reject(err);
});
};
});

return {
dataHandler: (data) => {
if (completed === true) {
debugLog(options, `Error: got ${fieldname}->${filename} data chunk for completed upload!`);
return;
}
if (writeStream === false) createWriteStream();
writeStream.write(data);
hash.update(data);
fileSize += data.length;
Expand All @@ -60,14 +52,12 @@ module.exports = (options, fieldname, filename) => {
},
cleanup: () => {
completed = true;
if (writeStream !== false) {
debugLog(options, `Cleaning up temporary file ${tempFilePath}...`);
writeStream.end();
deleteFile(tempFilePath, err => (err
? debugLog(options, `Cleaning up temporary file ${tempFilePath} failed: ${err}`)
: debugLog(options, `Cleaning up temporary file ${tempFilePath} done.`)
));
}
debugLog(options, `Cleaning up temporary file ${tempFilePath}...`);
writeStream.end();
deleteFile(tempFilePath, err => (err
? debugLog(options, `Cleaning up temporary file ${tempFilePath} failed: ${err}`)
: debugLog(options, `Cleaning up temporary file ${tempFilePath} done.`)
));
},
getWritePromise: () => writePromise
};
Expand Down

0 comments on commit d8c00c5

Please sign in to comment.