FileHelper.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const fs = require('fs');
  2. const path = require('path');
  3. // const images = require('images');
  4. let FileHelper = {
  5. // 返回图片占用内存(width*height*4)
  6. getImageMem(filePath, ext) {
  7. let memBytes = 0;
  8. // if ('.png' === ext || '.jpg' === ext || '.webp' === ext) {
  9. // memBytes = images(filePath).width() * images(filePath).height() * 4;
  10. // }
  11. return memBytes;
  12. },
  13. getFullPath(filePath) {
  14. if (!path.isAbsolute(filePath)) {
  15. filePath = path.join(__dirname, filePath); // 非绝对路径则加上当前目录
  16. }
  17. return filePath;
  18. },
  19. // 输出到文件
  20. writeFile(fullPath, content) {
  21. if (!fullPath || !content) {
  22. console.error('writeFile: invalid params');
  23. return;
  24. }
  25. fs.writeFile(fullPath, content, (err) => {
  26. if (err) {
  27. console.error(err);
  28. return;
  29. }
  30. console.log(content);
  31. console.log('Success to write file: ' + fullPath);
  32. });
  33. },
  34. // 返回文件内容的json对象
  35. getObjectFromFile(fullPath) {
  36. let retObj = {};
  37. if (!fs.existsSync(fullPath)) {
  38. console.error('getObjectFromFile: NoExist path=' +fullPath);
  39. return retObj;
  40. }
  41. let str = this.getFileString(fullPath);
  42. if (!str) {
  43. console.error('getObjectFromFile: invalid file=' +fullPath);
  44. return retObj;
  45. }
  46. retObj = JSON.parse(str);
  47. if (!retObj) {
  48. console.error('getObjectFromFile: invalid object=' +fullPath);
  49. return retObj;
  50. }
  51. return retObj;
  52. },
  53. // 返回文件内容的字符串形式
  54. getFileString(fullPath) {
  55. return fs.readFileSync(fullPath).toString();
  56. },
  57. // 函数防抖
  58. debounce(fn, wait = 1000) {
  59. var timeout = null;
  60. return function() {
  61. timeout && clearTimeout(timeout);
  62. timeout = setTimeout(fn, wait);
  63. }
  64. }
  65. };
  66. module.exports = FileHelper;