1 | const fs = require('fs');
|
2 | const path = require('path');
|
3 | const crypto = require('crypto');
|
4 | const {
|
5 | debugLog,
|
6 | checkAndMakeDir,
|
7 | getTempFilename,
|
8 | deleteFile
|
9 | } = require('./utilities');
|
10 |
|
11 | module.exports = (options, fieldname, filename) => {
|
12 | const dir = path.normalize(options.tempFileDir);
|
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;
|
21 | const promise = new Promise((resolve, reject) => {
|
22 | writeStream.on('finish', () => {
|
23 | resolve();
|
24 | });
|
25 | writeStream.on('error', (err) => {
|
26 | debugLog(options, `Error write temp file error:${err}`);
|
27 | reject(err);
|
28 | });
|
29 | });
|
30 |
|
31 | return {
|
32 | dataHandler: (data) => {
|
33 | writeStream.write(data);
|
34 | hash.update(data);
|
35 | fileSize += data.length;
|
36 | debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`);
|
37 | },
|
38 | getFilePath: () => tempFilePath,
|
39 | getFileSize: () => fileSize,
|
40 | getHash: () => hash.digest('hex'),
|
41 | complete: () => {
|
42 | writeStream.end();
|
43 |
|
44 | return Buffer.concat([]);
|
45 | },
|
46 | cleanup: () => {
|
47 | debugLog(options, `Cleaning up temporary file ${tempFilePath}...`);
|
48 | writeStream.end();
|
49 | deleteFile(tempFilePath, (err) => { if (err) throw err; });
|
50 | },
|
51 | getWritePromise: () => {
|
52 | return promise;
|
53 | }
|
54 | };
|
55 | };
|