UNPKG

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