writeFile.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const fs = require('fs');
  2. const path = require('path');
  3. module.exports = function(root, filePath, content) {
  4. let filePathList = filePath.split('/');
  5. let len = filePathList.length;
  6. let parentPath = root;
  7. if(!isFileExist(parentPath)) {
  8. try {
  9. fs.mkdirSync(parentPath);
  10. }
  11. catch(e) {
  12. console.log(e);
  13. }
  14. }
  15. filePathList.map((item, index) => {
  16. console.log('create html:', parentPath);
  17. let absPath = path.join(parentPath, item);
  18. if(!isFileExist(absPath)) {
  19. if(len - 1 !== index) {
  20. try {
  21. fs.mkdirSync(absPath);
  22. }
  23. catch(e) {
  24. console.log(e);
  25. }
  26. }
  27. }
  28. if(len - 1 === index) {
  29. try {
  30. fs.writeFileSync(absPath, content);
  31. }
  32. catch(e) {
  33. console.log(e);
  34. }
  35. }
  36. parentPath = absPath;
  37. })
  38. }
  39. function isFileExist(filePath) {
  40. try {
  41. fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
  42. return true;
  43. }
  44. catch(e) {
  45. return false;
  46. }
  47. }