hammer.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. const fs = require('fs');
  2. const path = require('path');
  3. function writeFile(root, filePath, content) {
  4. let sep = /\//;
  5. if(/\\/.test(root)) {
  6. filePath = filePath.replace(/\//g, '\\');
  7. sep = /\\/
  8. }
  9. let filePathList = filePath.split(sep);
  10. let len = filePathList.length;
  11. let parentPath = path.normalize(root);
  12. if(!this.isFileExist(parentPath)) {
  13. try {
  14. fs.mkdirSync(parentPath);
  15. }
  16. catch(e) {
  17. console.log(e);
  18. }
  19. }
  20. filePathList.map((item, index) => {
  21. let absPath = path.join(parentPath, item);
  22. if(!this.isFileExist(absPath)) {
  23. if(len - 1 !== index) {
  24. try {
  25. fs.mkdirSync(absPath);
  26. }
  27. catch(e) {
  28. console.log(e);
  29. }
  30. }
  31. }
  32. if(len - 1 === index) {
  33. try {
  34. fs.writeFileSync(absPath, content);
  35. }
  36. catch(e) {
  37. console.log(e);
  38. }
  39. }
  40. parentPath = absPath;
  41. })
  42. }
  43. function isFileExist(filePath) {
  44. try {
  45. fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
  46. return true;
  47. }
  48. catch(e) {
  49. return false;
  50. }
  51. }
  52. // 复制一个文件
  53. function copyFile(root, src, dst) {
  54. try {
  55. let content = fs.readFileSync(src, {
  56. encoding: 'utf8'
  57. });
  58. this.writeFile(root, dst.replace(root, ''), content);
  59. } catch (e) {
  60. console.log('copy Error', e);
  61. }
  62. }
  63. // 复制一个目录
  64. function copyDirSync(root, src, dst, ignoreList) {
  65. if(ignoreList === undefined) {
  66. ignoreList = [];
  67. }
  68. try {
  69. let demoFiles = fs.readdirSync(src);
  70. demoFiles.map(file => {
  71. if (ignoreList.indexOf(file) < 0) {
  72. let fileDir = path.join(src, file);
  73. let tarDir = path.join(dst, file);
  74. let stat = fs.statSync(fileDir);
  75. if (stat.isFile()) {
  76. this.copyFile(root, fileDir, tarDir);
  77. } else if (stat.isDirectory()) {
  78. // mkdir(tarDir);
  79. this.copyDirSync(root, fileDir, tarDir);
  80. }
  81. }
  82. });
  83. return true;
  84. } catch (e) {
  85. console.error('copyDirSync', e.message);
  86. return false;
  87. }
  88. }
  89. function Hammer() {
  90. this.writeFile = writeFile;
  91. this.isFileExist = isFileExist;
  92. this.copyFile = copyFile;
  93. this.copyDirSync = copyDirSync;
  94. }
  95. module.exports = new Hammer();