@kne/fastify-file-manager 3.0.0 → 3.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,39 +29,58 @@ module.exports = fp(async (fastify, fastifyOptions) => {
29
29
  const hash = crypto.createHash('md5');
30
30
  const extension = path.extname(filename);
31
31
  const tmpPath = path.resolve(os.tmpdir(), `temp_${filename}_${crypto.randomBytes(6).toString('hex')}`);
32
- const writeStream = fs.createWriteStream(tmpPath);
33
32
  let fileSize = 0;
34
33
  if (file.file) {
35
- file.file.on('data', chunk => {
36
- hash.update(chunk); // 更新哈希
37
- writeStream.write(chunk); // 写入文件
38
- fileSize += chunk.length; // 更新文件大小
39
- });
34
+ const writeStream = fs.createWriteStream(tmpPath);
40
35
 
41
36
  await new Promise((resolve, reject) => {
37
+ const cleanup = () => {
38
+ file.file.removeAllListeners();
39
+ writeStream.removeAllListeners();
40
+ };
41
+
42
+ const handleError = err => {
43
+ cleanup();
44
+ reject(err);
45
+ };
46
+
47
+ writeStream.on('error', handleError);
48
+ writeStream.on('drain', () => {
49
+ file.file.resume();
50
+ });
51
+
52
+ file.file.on('data', chunk => {
53
+ hash.update(chunk);
54
+ const canWrite = writeStream.write(chunk);
55
+ if (!canWrite) {
56
+ file.file.pause();
57
+ }
58
+ fileSize += chunk.length;
59
+ });
60
+
42
61
  file.file.on('end', () => {
43
- writeStream.end(); // 关闭写入流
62
+ writeStream.end();
63
+ });
64
+
65
+ file.file.on('error', handleError);
66
+ writeStream.on('finish', () => {
67
+ cleanup();
44
68
  resolve();
45
69
  });
46
- file.file.on('error', reject);
47
70
  });
48
- } else if (file.toBuffer) {
49
- const buffer = await file.toBuffer();
71
+ } else if (file.toBuffer || file.buffer) {
72
+ const buffer = file.toBuffer ? await file.toBuffer() : file.buffer;
50
73
  hash.update(buffer);
51
- writeStream.write(buffer);
74
+ await fs.writeFile(tmpPath, buffer);
52
75
  fileSize = buffer.byteLength;
53
- writeStream.end();
76
+ } else if (file.filepath) {
77
+ await fs.copy(file.filepath, tmpPath);
78
+ const stat = await fs.stat(tmpPath);
79
+ fileSize = stat.size;
54
80
  } else {
55
81
  throw new Error('文件类型不支持');
56
82
  }
57
83
 
58
- await new Promise((resolve, reject) => {
59
- writeStream.on('finish', () => {
60
- resolve();
61
- });
62
- writeStream.on('error', reject);
63
- });
64
-
65
84
  const digest = hash.digest('hex');
66
85
 
67
86
  let storageType;
@@ -99,18 +118,16 @@ module.exports = fp(async (fastify, fastifyOptions) => {
99
118
  file.options = options;
100
119
  await file.save();
101
120
  return file;
102
- })(() =>
103
- models.fileRecord.create({
104
- filename,
105
- namespace: namespace || fastifyOptions.namespace,
106
- encoding,
107
- mimetype,
108
- hash: digest,
109
- size: fileSize,
110
- storageType,
111
- options
112
- })
113
- );
121
+ })(() => models.fileRecord.create({
122
+ filename,
123
+ namespace: namespace || fastifyOptions.namespace,
124
+ encoding,
125
+ mimetype,
126
+ hash: digest,
127
+ size: fileSize,
128
+ storageType,
129
+ options
130
+ }));
114
131
  return Object.assign({}, outputFile.get({ plain: true }), { id: outputFile.uuid });
115
132
  };
116
133
 
@@ -165,10 +182,7 @@ module.exports = fp(async (fastify, fastifyOptions) => {
165
182
  }
166
183
 
167
184
  const tempFile = {
168
- filename,
169
- mimetype: response.headers.get('content-type'),
170
- encoding: 'binary',
171
- file: nodeStream
185
+ filename, mimetype: response.headers.get('content-type'), encoding: 'binary', file: nodeStream
172
186
  };
173
187
  return await uploadToFileSystem({ id, file: tempFile, namespace, options });
174
188
  };
@@ -203,9 +217,7 @@ module.exports = fp(async (fastify, fastifyOptions) => {
203
217
  targetFile = await ossServices.downloadFile({ filename: targetFileName });
204
218
  }
205
219
  return Object.assign({}, file.get({ pain: true }), {
206
- id: file.uuid,
207
- filePath: targetFileName,
208
- targetFile
220
+ id: file.uuid, filePath: targetFileName, targetFile
209
221
  });
210
222
  };
211
223
 
@@ -260,14 +272,10 @@ module.exports = fp(async (fastify, fastifyOptions) => {
260
272
  });
261
273
 
262
274
  const { count, rows } = await models.fileRecord.findAndCountAll({
263
- where: queryFilter,
264
- offset: perPage * (currentPage - 1),
265
- limit: perPage,
266
- order: [['createdAt', 'desc']]
275
+ where: queryFilter, offset: perPage * (currentPage - 1), limit: perPage, order: [['createdAt', 'desc']]
267
276
  });
268
277
  return {
269
- pageData: rows.map(item => Object.assign({}, item.get({ plain: true }), { id: item.uuid })),
270
- totalCount: count
278
+ pageData: rows.map(item => Object.assign({}, item.get({ plain: true }), { id: item.uuid })), totalCount: count
271
279
  };
272
280
  };
273
281
 
@@ -312,8 +320,7 @@ module.exports = fp(async (fastify, fastifyOptions) => {
312
320
  }
313
321
 
314
322
  return Object.assign({}, file.get({ plain: true }), {
315
- id: file.uuid,
316
- buffer
323
+ id: file.uuid, buffer
317
324
  });
318
325
  };
319
326
 
@@ -389,33 +396,23 @@ module.exports = fp(async (fastify, fastifyOptions) => {
389
396
  const tmpPath = path.resolve(os.tmpdir(), `temp_${id}_${crypto.randomBytes(6).toString('hex')}`);
390
397
  await compressing[type].uncompress(fileStream, tmpPath);
391
398
  const files = await glob(globOptions, {
392
- cwd: tmpPath,
393
- nodir: true
399
+ cwd: tmpPath, nodir: true
394
400
  });
395
401
  //将文件上传到文件系统
396
- const fileList = await Promise.all(
397
- files.map(async dir => {
398
- const filepath = path.resolve(tmpPath, dir);
399
- const filename = path.basename(dir);
400
- const fileStream = fs.createReadStream(filepath);
401
-
402
- const mimetype = MimeTypes.lookup(filepath) || 'application/octet-stream';
403
- const file = await uploadToFileSystem({
404
- file: {
405
- filename,
406
- mimetype,
407
- encoding: 'binary',
408
- file: fileStream
409
- },
410
- filename,
411
- namespace
412
- });
413
- return {
414
- dir,
415
- file
416
- };
417
- })
418
- );
402
+ const fileList = [];
403
+ for (let dir of files) {
404
+ const filepath = path.resolve(tmpPath, dir);
405
+ const filename = path.basename(dir);
406
+ const mimetype = MimeTypes.lookup(filepath) || 'application/octet-stream';
407
+ const file = await uploadToFileSystem({
408
+ file: {
409
+ filename, mimetype, encoding: 'binary', filepath
410
+ }, filename, namespace
411
+ });
412
+ fileList.push({
413
+ dir, file
414
+ });
415
+ }
419
416
  fs.remove(tmpPath).catch(console.error);
420
417
  return fileList;
421
418
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-file-manager",
3
- "version": "3.0.0",
3
+ "version": "3.0.1-alpha.1",
4
4
  "description": "用于管理静态文件上传查看等",
5
5
  "main": "index.js",
6
6
  "scripts": {