说明
主要是封装官方文档里面的
官方文档地址:https://www.html5plus.org/doc/zh_cn/io.html
创建或打开文件
//fileName 目录路径 dirEntry之前打开过的目录(没有则不填写)
function getFileEntry(fileName, dirEntry) {
return new Promise((resolve,reject) => {
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
let entry = dirEntry || fs.root;
entry.getFile(fileName, {
create: true
}, function(fileEntry) {
resolve(fileEntry);
}, function(e) {
reject(e);
});
});
})
}
创建或打开目录
function getDirEntry(dirName) {
return new Promise(async (resolve) => {
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
fs.root.getDirectory(dirName, {
create: true
}, function(dirEntry) {
resolve(dirEntry);
})
})
})
}
获取文件数据对象 fileName文件名路径 dirEntry文件夹路径(可以不填)
function getFile(fileName, dirEntry) {
return new Promise((resolve,reject) => {
getFileEntry(fileName, dirEntry).then(fileEntry=>{
fileEntry.file(function(file) {
file.close();
resolve(file);
},function(e){
file.close();
reject('失败');
});
})
})
}
获取文件内容 path文件路径 文件夹路径(可为空)
async function getFileContext(path, dirEntry) {
let deffered;
let fileReader = new plus.io.FileReader();
fileReader.onloadend = function(evt) {
deffered(evt.target);
}
let file = await getFile(path, dirEntry);
fileReader.readAsText(file, 'utf-8');
return new Promise((resolve) => {
deffered = resolve;
});
}
读取目录下所有文件
function getDirList(fileNamePath) {
return new Promise((resolve, reject) => {
let arr = [];
plus.io.resolveLocalFileSystemURL(
fileNamePath,
function(entry) {
var directoryReader = entry.createReader();
directoryReader.readEntries(
function(entries) {
for (var i = 0; i < entries.length; i++) {
// console.log("文件信息",entries[i].name);
arr.push(entries[i].name);
}
// console.log(arr);
resolve(arr);
// console.log(JSON.person(entries))
},
function(e) {
console.log('访问目录失败');
reject(e)
});
},
function(e) {
console.log('访问指定目录失败');
reject(e)
});
})
}
删除文件
function removeFlie(fliePath) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(fliePath, function(entry) {
entry.remove(function(entry) {
resolve(true);
}, function(e) {
console.log('删除失败',e);
reject(false)
});
}, function(e) {
console.log('访问路径失败')
reject(false)
})
})
}
标签:function,uniapp,dirEntry,console,io,读写操作,resolve,本地,reject
From: https://www.cnblogs.com/tn666/p/16986213.html