微信小程序 - 文件工具类 fileUtil.js
const fs = wx.getFileSystemManager();
function chooseMediaZip(options = {}){
const defaultOptions = { count: 9, mediaType: ['image']};
let params = {...defaultOptions, ...options};
return wx.chooseMedia(params)
.then(res=>{
return res.tempFiles.map(file => {
const arrayBuffer = readFileSync(file.tempFilePath, '', 26);
console.log(arrayBuffer);
const zipFile = {};
zipFile.name = `${Date.now()}.zip`;
zipFile.path =`${ params.zippng }/${ zipFile.name }`;
mkdir(params.zippng);
writeFileSync( zipFile.path, arrayBuffer, 'binary' );
return zipFile;
});
}).catch(console.error);
}
function chooseMedia(options = {}){
const defaultOptions = { count: 9, mediaType: ['image']};
return wx.chooseMedia({...defaultOptions, ...options});
}
function chooseFile(_count){
return wx.chooseMessageFile({ count: _count })
.then( res => {
if(res.errMsg === "chooseMessageFile:ok"){
return res.tempFiles;
}else{
return [];
}
});
}
function ls(rootPath) {
if(!isExist(rootPath)){
return [];
}
let list = fs.statSync(`${rootPath}`, true);
if(Array.isArray(list) == false && list.isDirectory()) {
return [];
}
return list.map(df => {
df.type = df.stats.isFile() ? 'file' : 'dir';
return df;
}).reduce((result, item) => {
item.path = `${rootPath}/${item.path}`;
result[item.type].push(item);
return result;
}, {'file':[], 'dir': []});
}
function unlinkSync(filePath){
if(isExist(filePath) == false){
console.log(`文件不存在:${filePath}`)
return;
}
try {
const res = fs.unlinkSync(filePath);
console.log(res)
} catch(e) {
console.error(e)
}
}
function clearDir(rootPath, saveSelf=true) {
if(!isExist(rootPath)){
return;
}
let group = ls(rootPath);
if(Array.isArray(group.file) == false){
return;
}
let p = group.file.map(f => {
return new Promise((resolve, reject) => {
fs.unlink({
filePath: f.path,
success: res => resolve(res),
fail: err => reject(err)
})
});
});
Promise.all(p).then(res => {
fs.rmdir({
dirPath: `${rootPath}`,
recursive: true,
success: res => console.log(res),
fail: err => console.error(err),
});
});
if(saveSelf){
mkdir(rootPath);
}
}
function clearDirSync(rootPath, saveSelf=true) {
if(!isExist(rootPath)){
return;
}
let group = ls(rootPath);
if(Array.isArray(group.file) == false){
return;
}
group.file.map(f => fs.unlinkSync(f.path));
fs.rmdirSync(rootPath, true);
if(saveSelf){
mkdir(rootPath);
}
}
function clearFilesSync(rootPath) {
try {
const files = fs.readdirSync(rootPath);
files.forEach(path => fs.unlinkSync(`${rootPath}/${path}`));
return files;
} catch (error) {
console.error(error);
}
}
function isExist(path){
try {
fs.accessSync(path);
return true;
} catch (err) {
console.log(`文件或目录不存在:${err.message}`);
return false;
}
}
function mkdir(path, recursive = true){
if(isExist(path) == false){
fs.mkdirSync(path, recursive);
}
}
function rmdirSync(path, recursive=false){
if(isExist(path)){
fs.rmdirSync(path, recursive);
}
}
function addSuffixNumber(fileName, suffixNumber, suffixLen) {
let extension = '';
let index = fileName.lastIndexOf('.');
if (index !== -1) {
extension = fileName.substring(index);
fileName = fileName.substring(0, index);
}
let suffixLength = Math.floor(Math.log10(suffixLen)) + 1;
let paddedSuffixNumber = String(suffixNumber).padStart(suffixLength, '0');
return `${fileName}_${paddedSuffixNumber}${extension}`;
}
function padNumber(num, count=10, suffixStr='0') {
let suffixLength = Math.floor(Math.log10(count)) + 1;
return String(num).padStart(suffixLength, suffixStr);
}
function getFileInfo(filePath) {
const folderPath = filePath.substring(0, filePath.lastIndexOf('/') + 1);
const fileName = filePath.substring(folderPath.length, filePath.lastIndexOf('.'));
const fileExtension = filePath.substring(filePath.lastIndexOf('.') + 1);
return {
path: folderPath,
fullName: `${fileName}.${fileExtension}`,
name: fileName,
extension: fileExtension
};
}
function readFileSync(filePath, encoding='', position=0, length) {
return fs.readFileSync(filePath, encoding, position, length);
}
function writeFileSync(filePath, data, encoding='binary') {
fs.writeFileSync(filePath, data, encoding);
}
module.exports = {
fs,
chooseMediaZip,
chooseMedia,
chooseFile,
ls,
unlinkSync,
clearDir,
clearDirSync,
clearFilesSync,
isExist,
mkdir,
rmdirSync,
addSuffixNumber,
padNumber,
readFileSync,
writeFileSync
};