saveFiles_cjs.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const fs = require('fs');
  2. const path = require('path');
  3. const {handle} = require("./handle_cjs");
  4. async function mvFile(file, targetPath, newFileName, maxRename = 10 , renameTotal = 0){
  5. try {
  6. // 判断路径是否存在,不存在则创建
  7. let err, exists;
  8. [err] = await handle(fs.promises.mkdir(targetPath, {recursive: true}));
  9. if (err) {
  10. return [err, null];
  11. }
  12. // 拼接新的文件路径
  13. let newFilePath = path.join(targetPath, newFileName);
  14. let ext = null;
  15. let name = null;
  16. let newName = '';
  17. // 判断文件是否存在
  18. [err, exists] = await handle(fs.existsSync(newFilePath));
  19. if (err) {
  20. return [err, null];
  21. }
  22. // 如果文件存在,则重命名在最后加上 _n n为数字
  23. if (exists) {
  24. renameTotal++;// 1
  25. if (renameTotal >= maxRename) {
  26. return [{message: `重命名次数超过最大值`}, null];
  27. }
  28. ext = path.extname(newFileName);
  29. name = path.basename(newFileName, ext)
  30. newName = `${name}_${renameTotal}${ext}`;
  31. newFilePath = path.join(targetPath, newName);
  32. [err, exists] = await handle(fs.existsSync(newFilePath));
  33. if (err) {
  34. return [err, null];
  35. }
  36. if(exists){
  37. return await mvFile(file, targetPath, newFileName, maxRename, renameTotal);
  38. }
  39. }
  40. // console.log(file);
  41. // 移动文件
  42. [err] = await handle(fs.promises.rename(file.filepath, newFilePath));
  43. if (err) {
  44. return [err, null];
  45. }
  46. return [null, newName || newFileName];
  47. } catch (e) {
  48. return [e, null];
  49. }
  50. }
  51. async function rmFile(filePath){
  52. // 判断是否为文件夹
  53. let err, stats ,res;
  54. [err, stats] = await handle(fs.promises.stat(filePath));
  55. if(err){
  56. return [err,null];
  57. }
  58. if(stats.isDirectory()){
  59. return [{message:`${filePath} 为文件夹`},null];
  60. }
  61. // 删除文件
  62. [err,res] = await handle(fs.promises.unlink(filePath));
  63. if(err){
  64. return [err,null];
  65. }
  66. return [null,res];
  67. }
  68. module.exports = {
  69. mvFile,
  70. rmFile
  71. }