const fs = require('fs'), path = require('path'), fsExports = {};/** * @description 获取编码方式 * @method suffixHandle * @param pathname {String} * @return String */let suffixHandle = (pathname) => { let suffixReg = /\.([0-9a-zA-Z]+)$/, suffix = suffixReg.test(pathname) ? suffixReg.exec(pathname)[1] : '', encoding = 'utf8', suffixFormatting = /^(png|jpeg|svg|webp|bmp|ico|mp3|mp4|wav|ogg|m3u8)$/i; suffixFormatting.test(suffix) ? encoding = null : null; return encoding;};/** * @description 将用户传入的路径转换为绝对路径 * @method getName * @param pathname {String} * @return String */let getName = pathname => path.resolve(pathname);// 读取文件['readFile', 'readdir', 'mkdir', 'rmdir', 'unlink'].forEach(item => { fsExports[item] = anonymous = (pathname) => { pathname = getName(pathname); return new Promise((resolve, reject) => { let encoding = suffixHandle(pathname), callback = (err, result) => { if (err) reject(err); resolve(result); }; if (item !== 'readFile') { encoding = callback; callback = null; } fs[item](pathname, encoding, callback); }); };});// 写入文件['writeFile', 'appendFile'].forEach(item => { fsExports[item] = anonymous = (pathname, content) => { content !== null && typeof content === 'object' ? content = JSON.stringify(content) : null; typeof content !== 'string' ? content += '' : null; pathname = getName(pathname); return new Promise((resolve, reject) => { let encoding = suffixHandle(pathname); fs[item](pathname, content, encoding, err => { if (err) reject(err); resolve('文件操作成功'); }) }) }});// 复制文件fsExports['copyFile'] = anonymous = (pathname, content) => { content !== null && typeof content === 'object' ? content = JSON.stringify(content) : null; typeof content !== 'string' ? content += '' : null; pathname = getName(pathname); return new Promise((resolve, reject) => { let encoding = suffixHandle(pathname); fs[item](pathname, content, encoding, err => { if (err) reject(err); resolve('文件操作成功'); }) })};module.exports = {...fsExports};