合同小程序前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.4 KiB

3 months ago
  1. const fs = require("fs");
  2. const glob = require('glob');
  3. const path = require("path");
  4. const rootPath = process.cwd(); // 获取根目录
  5. // https://bl.ocks.org/jennyknuth/222825e315d45a738ed9d6e04c7a88d0
  6. function encodeSvg(svg) {
  7. return svg
  8. .replace(
  9. "<svg",
  10. ~svg.indexOf("xmlns") ? "<svg" : '<svg xmlns="http://www.w3.org/2000/svg"'
  11. )
  12. .replace(/"/g, "'")
  13. .replace(/%/g, "%25")
  14. .replace(/#/g, "%23")
  15. .replace(/{/g, "%7B")
  16. .replace(/}/g, "%7D")
  17. .replace(/</g, "%3C")
  18. .replace(/>/g, "%3E");
  19. }
  20. function isDirectoryEmpty(path) {
  21. const files = fs.readdirSync(path);
  22. return files.length === 0;
  23. }
  24. function deleteFolderBFS(folderPath) {
  25. const outputPath = /^\.|\/|\\/.test(folderPath) ? path.join(rootPath, folderPath): folderPath
  26. if(!fs.existsSync(outputPath)) {
  27. return
  28. }
  29. const queue = [outputPath];
  30. while (queue.length > 0) {
  31. const currentPath = queue.shift();
  32. const currentStats = fs.statSync(currentPath);
  33. if (currentStats.isDirectory()) {
  34. const files = fs.readdirSync(currentPath);
  35. for (const file of files) {
  36. const filePath = path.join(currentPath, file);
  37. const fileStats = fs.statSync(filePath);
  38. if (fileStats.isDirectory()) {
  39. queue.push(filePath);
  40. } else {
  41. fs.unlinkSync(filePath); // 删除文件
  42. }
  43. }
  44. if(isDirectoryEmpty(currentPath)) {
  45. fs.rmdirSync(currentPath);
  46. }
  47. }
  48. }
  49. }
  50. // 保存
  51. async function saveFile(file, data) {
  52. const outputPath = /^(\.|\/|\\)/.test(file) ? path.join(rootPath, file) : file;
  53. const outputDir = path.dirname(outputPath);
  54. try {
  55. // 创建文件夹
  56. await fs.promises.mkdir(outputDir, {
  57. recursive: true
  58. });
  59. // 使用 Promise 进行写入文件操作
  60. await fs.promises.writeFile(outputPath, data, "utf8");
  61. // console.log(`成功保存文件:${outputPath}`);
  62. } catch (error) {
  63. console.error("保存文件时出错:", error);
  64. }
  65. }
  66. // 可选的选项对象
  67. const customOptions = {
  68. prefix: "l", // 为图标集设置前缀
  69. includeSubDirs: true, // 启用扫描子目录中的文件(默认启用)
  70. keyword: (fileName, defaultKeyword, iconSet) => {
  71. // 根据文件名自定义关键字生成
  72. // 返回关键字或 undefined 以跳过该文件
  73. return defaultKeyword;
  74. },
  75. ignoreImportErrors: true, // 禁用未成功导入图标时的错误抛出(默认启用)
  76. keepTitles: false, // 禁用在 SVG 中保留标题(默认禁用)
  77. };
  78. module.exports = {
  79. encodeSvg,
  80. saveFile,
  81. deleteDirectory: deleteFolderBFS,
  82. customOptions,
  83. };