1. const fs = require('fs'),
    2. path = require('path'),
    3. fsExports = {};
    4. /**
    5. * @description 获取编码方式
    6. * @method suffixHandle
    7. * @param pathname {String}
    8. * @return String
    9. */
    10. let suffixHandle = (pathname) => {
    11. let suffixReg = /\.([0-9a-zA-Z]+)$/,
    12. suffix = suffixReg.test(pathname) ? suffixReg.exec(pathname)[1] : '',
    13. encoding = 'utf8',
    14. suffixFormatting = /^(png|jpeg|svg|webp|bmp|ico|mp3|mp4|wav|ogg|m3u8)$/i;
    15. suffixFormatting.test(suffix) ? encoding = null : null;
    16. return encoding;
    17. };
    18. /**
    19. * @description 将用户传入的路径转换为绝对路径
    20. * @method getName
    21. * @param pathname {String}
    22. * @return String
    23. */
    24. let getName = pathname => path.resolve(pathname);
    25. // 读取文件
    26. ['readFile', 'readdir', 'mkdir', 'rmdir', 'unlink'].forEach(item => {
    27. fsExports[item] = anonymous = (pathname) => {
    28. pathname = getName(pathname);
    29. return new Promise((resolve, reject) => {
    30. let encoding = suffixHandle(pathname),
    31. callback = (err, result) => {
    32. if (err) reject(err);
    33. resolve(result);
    34. };
    35. if (item !== 'readFile') {
    36. encoding = callback;
    37. callback = null;
    38. }
    39. fs[item](pathname, encoding, callback);
    40. });
    41. };
    42. });
    43. // 写入文件
    44. ['writeFile', 'appendFile'].forEach(item => {
    45. fsExports[item] = anonymous = (pathname, content) => {
    46. content !== null && typeof content === 'object' ? content = JSON.stringify(content) : null;
    47. typeof content !== 'string' ? content += '' : null;
    48. pathname = getName(pathname);
    49. return new Promise((resolve, reject) => {
    50. let encoding = suffixHandle(pathname);
    51. fs[item](pathname, content, encoding, err => {
    52. if (err) reject(err);
    53. resolve('文件操作成功');
    54. })
    55. })
    56. }
    57. });
    58. // 复制文件
    59. fsExports['copyFile'] = anonymous = (pathname, content) => {
    60. content !== null && typeof content === 'object' ? content = JSON.stringify(content) : null;
    61. typeof content !== 'string' ? content += '' : null;
    62. pathname = getName(pathname);
    63. return new Promise((resolve, reject) => {
    64. let encoding = suffixHandle(pathname);
    65. fs[item](pathname, content, encoding, err => {
    66. if (err) reject(err);
    67. resolve('文件操作成功');
    68. })
    69. })
    70. };
    71. module.exports = {...fsExports};