1 | 'use strict';
|
2 |
|
3 | const fs = require('fs');
|
4 | const path = require('path');
|
5 | const Readable = require('stream').Readable;
|
6 |
|
7 |
|
8 | const SAFE_FILE_NAME_REGEX = /[^\w-]/g;
|
9 | const MAX_EXTENSION_LENGTH = 3;
|
10 |
|
11 |
|
12 | const TEMP_COUNTER_MAX = 65536;
|
13 | const TEMP_PREFIX = 'tmp';
|
14 | let tempCounter = 0;
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | const debugLog = (options, msg) => {
|
23 | options = options || {};
|
24 | if (!options.debug) return false;
|
25 | console.log(msg);
|
26 | return true;
|
27 | };
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | const getTempFilename = (prefix) => {
|
35 | prefix = prefix || TEMP_PREFIX;
|
36 | tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1;
|
37 | return `${prefix}-${tempCounter}-${Date.now()}`;
|
38 | };
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | const isFunc = func => func && func.constructor && func.call && func.apply ? true: false;
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | const errorFunc = (resolve, reject) => isFunc(reject) ? reject : resolve;
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | const promiseCallback = (resolve, reject) => {
|
57 | return err => err ? errorFunc(resolve, reject)(err) : resolve();
|
58 | };
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | const buildOptions = function(){
|
65 | const result = {};
|
66 | [...arguments].forEach(options => {
|
67 | if (!options || typeof options !== 'object') return;
|
68 | Object.keys(options).forEach(key => result[key] = options[key]);
|
69 | });
|
70 | return result;
|
71 | };
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 | const buildFields = (instance, field, value) => {
|
81 |
|
82 | if (value === null || value === undefined) return instance;
|
83 | instance = instance || {};
|
84 |
|
85 | if (!instance[field]) {
|
86 | instance[field] = value;
|
87 | } else {
|
88 |
|
89 | if (instance[field] instanceof Array) {
|
90 | instance[field].push(value);
|
91 | } else {
|
92 | instance[field] = [instance[field], value];
|
93 | }
|
94 | }
|
95 | return instance;
|
96 | };
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 | const checkAndMakeDir = (fileUploadOptions, filePath) => {
|
105 |
|
106 | if (!fileUploadOptions) return false;
|
107 | if (!fileUploadOptions.createParentPath) return false;
|
108 |
|
109 | if (!filePath) return false;
|
110 | const parentPath = path.dirname(filePath);
|
111 |
|
112 | if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true });
|
113 |
|
114 | return fs.existsSync(parentPath);
|
115 | };
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 | const deleteFile = (file, callback) => fs.unlink(file, err => err ? callback(err) : callback());
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 | const copyFile = (src, dst, callback) => {
|
129 |
|
130 | let cbCalled = false;
|
131 | let runCb = (err) => {
|
132 | if (cbCalled) return;
|
133 | cbCalled = true;
|
134 | callback(err);
|
135 | };
|
136 |
|
137 | let readable = fs.createReadStream(src);
|
138 | readable.on('error', runCb);
|
139 |
|
140 | let writable = fs.createWriteStream(dst);
|
141 | writable.on('error', (err)=>{
|
142 | readable.destroy();
|
143 | runCb(err);
|
144 | });
|
145 | writable.on('close', () => runCb());
|
146 |
|
147 | readable.pipe(writable);
|
148 | };
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 | const moveFile = (src, dst, callback) => {
|
157 | fs.rename(src, dst, err => {
|
158 | if (err) {
|
159 |
|
160 | copyFile(src, dst, err => err ? callback(err) : deleteFile(src, callback));
|
161 | return;
|
162 | }
|
163 | callback();
|
164 | });
|
165 | };
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 | const saveBufferToFile = (buffer, filePath, callback) => {
|
173 | if (!Buffer.isBuffer(buffer)) {
|
174 | return callback(new Error('buffer variable should be type of Buffer!'));
|
175 | }
|
176 |
|
177 | let streamData = buffer;
|
178 | let readStream = Readable();
|
179 | readStream._read = () => {
|
180 | readStream.push(streamData);
|
181 | streamData = null;
|
182 | };
|
183 |
|
184 | let fstream = fs.createWriteStream(filePath);
|
185 | fstream.on('error', error => callback(error));
|
186 | fstream.on('close', () => callback());
|
187 |
|
188 | readStream.pipe(fstream);
|
189 | };
|
190 |
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 | const uriDecodeFileName = (opts, fileName) => {
|
197 | return opts.uriDecodeFileNames ? decodeURIComponent(fileName) : fileName;
|
198 | };
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 |
|
206 | const parseFileNameExtension = (preserveExtension, fileName) => {
|
207 | const preserveExtensionLengh = parseInt(preserveExtension);
|
208 | const result = {name: fileName, extension: ''};
|
209 | if (!preserveExtension && preserveExtensionLengh !== 0) return result;
|
210 |
|
211 | const maxExtLength = isNaN(preserveExtensionLengh)
|
212 | ? MAX_EXTENSION_LENGTH
|
213 | : Math.abs(preserveExtensionLengh);
|
214 |
|
215 | const nameParts = fileName.split('.');
|
216 | if (nameParts.length < 2) return result;
|
217 |
|
218 | let extension = nameParts.pop();
|
219 | if (
|
220 | extension.length > maxExtLength &&
|
221 | maxExtLength > 0
|
222 | ) {
|
223 | nameParts[nameParts.length - 1] +=
|
224 | '.' +
|
225 | extension.substr(0, extension.length - maxExtLength);
|
226 | extension = extension.substr(-maxExtLength);
|
227 | }
|
228 |
|
229 | result.extension = maxExtLength ? extension : '';
|
230 | result.name = nameParts.join('.');
|
231 | return result;
|
232 | };
|
233 |
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 | const parseFileName = (opts, fileName) => {
|
241 |
|
242 | let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255);
|
243 |
|
244 | parsedName = uriDecodeFileName(opts, parsedName);
|
245 |
|
246 | if (!opts.safeFileNames) return parsedName;
|
247 |
|
248 | const nameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp
|
249 | ? opts.safeFileNames
|
250 | : SAFE_FILE_NAME_REGEX;
|
251 |
|
252 | let {name, extension} = parseFileNameExtension(opts.preserveExtension, parsedName);
|
253 | if (extension.length) extension = '.' + extension.replace(nameRegex, '');
|
254 |
|
255 | return name.replace(nameRegex, '').concat(extension);
|
256 | };
|
257 |
|
258 | module.exports = {
|
259 | debugLog,
|
260 | isFunc,
|
261 | errorFunc,
|
262 | promiseCallback,
|
263 | buildOptions,
|
264 | buildFields,
|
265 | checkAndMakeDir,
|
266 | deleteFile,
|
267 | copyFile,
|
268 | moveFile,
|
269 | saveBufferToFile,
|
270 | parseFileName,
|
271 | getTempFilename,
|
272 | uriDecodeFileName
|
273 | };
|