tempFileHandler.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const fs = require('fs');
  2. const path = require('path');
  3. const crypto = require('crypto');
  4. const {
  5. debugLog,
  6. checkAndMakeDir,
  7. getTempFilename
  8. } = require('./utilities');
  9. module.exports = (options, fieldname, filename) => {
  10. const dir = path.normalize(options.tempFileDir || process.cwd() + '/tmp/');
  11. const tempFilePath = path.join(dir, getTempFilename());
  12. checkAndMakeDir({createParentPath: true}, tempFilePath);
  13. let hash = crypto.createHash('md5');
  14. let writeStream = fs.createWriteStream(tempFilePath);
  15. let fileSize = 0; // eslint-disable-line
  16. return {
  17. dataHandler: (data) => {
  18. writeStream.write(data);
  19. hash.update(data);
  20. fileSize += data.length;
  21. debugLog(options, `Uploading ${fieldname} -> ${filename}, bytes: ${fileSize}`);
  22. },
  23. getFilePath: () => tempFilePath,
  24. getFileSize: () => fileSize,
  25. getHash: () => hash.digest('hex'),
  26. complete: () => {
  27. writeStream.end();
  28. //return empty buffer since data uploaded to the temporary file.
  29. return Buffer.concat([]);
  30. },
  31. cleanup: () => {
  32. writeStream.end();
  33. fs.unlink(tempFilePath, (err) => {
  34. if (err) throw err;
  35. });
  36. }
  37. };
  38. };