File System 之本地文件系统
上一篇文章提到了,最近做一个基于 File System/IndexedDB的应用,上一篇是定额和使用的查询。
因为LocalFileSystem只有chrome支持,有点尴尬,如果按需加载又何来尴尬。
这一篇是关于文件和目录的操作的,怕陷入回调陷阱,基于promise和ES7的await。
首先介绍两个函数:
/**
* 转为promise,主要是把 a.b(param1,param2,successCallback,errorCall) 转为promise
* @param {*期待的是函数} obj
* @param {*上下文} ctx
* @param {*参数} args
*/
function toPromise(obj, ctx = window, ...args) {
if (!obj) return obj //如果已经是Promise对象
if ('function' == typeof obj.then) return obj //若obj是函数直接转换
if ('function' == typeof obj) return _toPromise(obj) return obj; //函数转成 promise
function _toPromise(fn) {
return new Promise((resolve, reject) => { fn.call(ctx, ...args, (...ags) => {
//多个参数返回数组,单个直接返回对象
resolve(ags && ags.length > 1 ? ags : ags[0] || null)
}, (err) => {
reject(err)
}) })
}
}
第二个是 promiseForEach,顺序的执行多个Promise,思想也就是then的拼接
/**
* https://segmentfault.com/q/1010000007499416
* Promise for forEach
* @param {*数组} arr
* @param {*回调} cb(val)返回的应该是Promise
* @param {*是否需要执行结果集} needResults
*/
function promiseForEach(arr, cb, needResults) {
let realResult = [], lastResult //lastResult参数暂无用
let result = Promise.resolve()
Array.from(arr).forEach((val, index) => {
result = result.then(() => {
return cb(val, index).then((res) => {
lastResult = res
needResults && realResult.push(res)
})
})
}) return needResults ? result.then(() => realResult) : result
}
这两个方法完毕后,就直接上主体代码了, hold on。
/**
* 参考的API:
* http://w3c.github.io/quota-api/
*
*/ if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
//文件系统请求标识
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem
//根据URL取得文件的读取权限
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL //临时储存和永久存储
navigator.temporaryStorage = navigator.temporaryStorage || navigator.webkitTemporaryStorage;
navigator.persistentStorage = navigator.persistentStorage || navigator.webkitPersistentStorage; //常量
const _TEMPORARY = 'temporary',
_PERSISTENT = 'persistent',
FS_SCHEME = 'filesystem:' class LocalFileSystem { constructor(fs) {
this._fs = fs //文件系统
this._root = fs.root //文件系统的根Entry
this._instance = null //示例对象
this._type = null //类型,window.TEMPORAR| window.PERSISTENT
this._fsBaseUrl = null //文件系统的基础地址
} /**
*
* @param {* window.TEMPORAR(0) |window.PERSISTENT(1)} type
* @param {* 申请空间大小,单位为M } size
*/
static getInstance(type = window.TEMPORARY, size = 1) { if (this._instance) {
return Promise.resolve(this._instance)
}
//类型
let typeValue = type,
//文件系统基础地址
fsBaseUrl = FS_SCHEME + location.origin + '/' + (type == 1 ? _PERSISTENT : _TEMPORARY) + '/'
return new Promise((resolve, reject) => {
window.requestFileSystem(type, size * 1024 * 1024, fs => {
this._instance = new LocalFileSystem(fs)
this._instance._type = typeValue;
this._instance._fsBaseUrl = fsBaseUrl
return resolve(this._instance)
}, (err) => reject(err))
}) } /**
* 获得FileEntry
* @param {*文件路径} path
*/
_getFileEntry(path, create = false) {
return toPromise(this._root.getFile, this._root, path, { create, exclusive: false })
} /**
* 获取目录
* @param {*路径} path
* @param {*不存在的时候是否创建} create
*/
_getDirectory(path = '', create = false) {
return toPromise(this._root.getDirectory, this._root, path, { create, exclusive: false })
} async _readEntriesRecursively(rootEntry, refResults) { if (rootEntry.isFile) {
return Promise.resolve(rootEntry)
}
let reader = rootEntry.createReader()
let entries = await toPromise(reader.readEntries, reader)
refResults.push(...entries)
let psEntries = entries.map(entry => this._readEntriesRecursively(entry, refResults))
return Promise.all(psEntries)
} /**
* 获得Entry
* @param {*路径} path
*/
resolveLocalFileSystemURL(path) {
return toPromise(window.resolveLocalFileSystemURL, window, `${this._fsBaseUrl}${path.startsWith('\/') ? path.substr(1) : path}`)
} /**
* 获得文件
* @param {*文件路径} path
*/
async getFile(path) {
let fe = await this._getFileEntry(path)
return toPromise(fe.file, fe)
} /**
* 往文件写入内容
* @param {*文件路径} path
* @param {*写入的内容} content
* @param {*数据类型} type
* @param {*是否是append} append
*/
async writeToFile(path, content, type = 'text/plain', append = false) { let fe = await this._getFileEntry(path, true)
let writer = await toPromise(fe.createWriter, fe);
let data = content; //不是blob,转为blob
if (content instanceof ArrayBuffer) {
data = new Blob([new Uint8Array(content)], { type })
} else if (typeof content == 'string') {
data = new Blob([content], { type: 'text/plain' })
} else {
data = new Blob([content])
} if (append) {
writer.seek(writer.length)
} return new Promise((resolve, reject) => {
//写入成功
writer.onwriteend = () => {
resolve(true)
} //写入失败
writer.onerror = (err) => {
reject(err)
} writer.write(data)
})
} /**
* 获取指定目录下的文件和文件夹
* @param {*路径} path
*/
async readEntries(path = '') {
let entry = null
if (!path) {
entry = this._root
} else {
entry = await this.resolveLocalFileSystemURL(path)
}
let reader = entry.createReader()
return toPromise(reader.readEntries, reader);
} /**
* 获取所有的文件和文件夹,按照路径排序
*/
async readAllEntries() {
let refResults = []
let entries = await this._readEntriesRecursively(this._root, refResults)
refResults.sort((a, b) => a.fullPath > b.fullPath)
return refResults } /**
* 确认目录存在,递归检查,没有会自动创建
* @param {*} directory
*/
async ensureDirectory(directory = '') {
//过滤空的目录,比如 '/music/' => ['','music','']
let _dirs = directory.split('/').filter(v => !!v) if (!_dirs || _dirs.length == 0) {
return Promise.resolve(true)
} return promiseForEach(_dirs, (dir, index) => {
return this._getDirectory(_dirs.slice(0, index + 1).join('/'), true)
}, true).then((rs) => {
console.log(rs)
return true
})
} /**
* 清除所有的文件和文件夹
*/
async clear() {
let entries = await this.readEntries()
let ps_entries = entries.map(e => e.isFile ? toPromise(e.remove, e) : toPromise(e.removeRecursively, e))
return Promise.all(ps_entries)
} /**
* Promise里面的错误处理
* @param {*reject}
*/
errorHandler(reject) {
return (error) => {
reject(error)
}
} } // 测试语句
//读取某个目录的子目录和文件: LocalFileSystem.getInstance().then(fs=>fs.readEntries()).then(f=>console.log(f))
//写文件 LocalFileSystem.getInstance().then(fs=>fs.writeToFile('music/txt.txt','爱死你')).then(f=>console.log(f))
//获取文件: LocalFileSystem.getInstance().then(fs=>fs.getFile('music/txt.txt')).then(f=>console.log(f))
//递归创建目录: LocalFileSystem.getInstance().then(fs=>fs.ensureDirectory('music/vbox')).then(r=>console.log('r:' + r))
//递归获取: LocalFileSystem.getInstance().then(fs=>fs.readAllEntries()).then(f=>console.log(f))
//删除所有: LocalFileSystem.getInstance().then(fs=>fs.clear()).then(f=>console.log(f)).catch(err=>console.log(err))
当然测试语句也在上面了,因为用了 await,那么大家自然知道了。需要 chrome://flags开启javascript的特性。
如果你有兴趣,代码地址:https://github.com/xiangwenhu/BlogCodes/tree/master/client/FileSystem,下载下来
npm install 之后, node server/app.js就可以查询demo了
File System 之本地文件系统的更多相关文章
- [LeetCode] Design In-Memory File System 设计内存文件系统
Design an in-memory file system to simulate the following functions: ls: Given a path in string form ...
- chattr lsattr linux file system attributes - linux 文件系统扩展属性
我们使用 linux 文件系统扩展属性,能够对linux文件系统进行进一步保护:从而给文件 赋予一些额外的限制:在有些情况下,能够对我们的系统提供保护: chattr命令用来改变文件属性.这项指令可改 ...
- GFS(Google File System,谷歌文件系统)----(1)文件系统简介
分布式文件系统 系统是构建在普通的.廉价的机器上,因此故障是常态而不是意外 系统希望存储的是大量的大型文件(单个文件size很大) 系统支持两种类型读操作:大量的顺序读取以及小规模的随机读取(larg ...
- GFS(Google File System,谷歌文件系统)----(1)读写一致性
GFS副本控制协议--中心化副本控制协议 对于副本集的更新操作有一个中心节点来协调管理,将分布式的并发操作转化为单点的并发操作,从而保证副本集内各节点的一致性.在GFS中,中心节点称之为Primary ...
- HDFS(Hadoop Distributed File System )
HDFS(Hadoop Distributed File System ) HDFS(Hadoop Distributed File System )Hadoop分布式文件系统.是根据google发表 ...
- Fast File System
不扯淡了,直接来写吧,一天一共要写三篇博客,还有两篇呢. 1. 这篇博客讲什么? Fast File System(FFS)快速文件系统,基本思想已经在在上一篇博客File System Implem ...
- File System Implementation 文件系统设计实现
先来扯淡吧,上一篇文章说到要补习的第二篇文章介绍文件系统的,现在就来写吧.其实这些技术都已经是很久以前的了,但是不管怎么样,是基础,慢慢来学习吧.有种直接上Spark源码的冲动.. 1. 这篇博客具体 ...
- HTML5之本地文件系统API - File System API
HTML5之本地文件系统API - File System API 新的HTML5标准给我们带来了大量的新特性和惊喜,例如,画图的画布Canvas,多媒体的audio和video等等.除了上面我们提到 ...
- HDFS(Hadoop Distributed File System )hadoop分布式文件系统。
HDFS(Hadoop Distributed File System )hadoop分布式文件系统.HDFS有如下特点:保存多个副本,且提供容错机制,副本丢失或宕机自动恢复.默认存3份.运行在廉价的 ...
随机推荐
- springboot(一)
1,使用springboot开发需要以下配置: : Maven | Gradle | Ant | Starters code工具:IDE | Packaged | Maven | Gradle 系统要 ...
- day9、用户登陆出现-bash-4.1$错误的原因及解决方法
原因:用户家目录里面与环境变量有关的文件被删除所导致的 下面两个文件被删除导致的 .bash_profile .bashrc 解决方法:从/etc/skel把丢失的文件 复制回来就可以了 -bash- ...
- 【new File(String Path)加载资源问题】
2017-12-17 15:07:38 [原创-wx] 一.我们在用IO流加载资源的时候,创建文件资源 1 File file = New File("String Path" ...
- C#中的Explicit和Implicit
今天在Review一个老项目的时候,看到一段奇怪的代码. if (dto.Payment == null) continue; var entity = entries.FirstOrDefault( ...
- 载入DLL中的图片资源生成Skia中的SkBitmap对象
PPAPI Plugin在Windows下是DLL,能够嵌入图片文件.使用Skia画图时须要依据DLL里的图片文件生成SkBitmap对象. 以下是代码: #include "utils.h ...
- java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
1.错误描写叙述 java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). at c ...
- Nginx服务编译安装、日志功能、状态模块及访问认证模式实操
系统环境 [root@web ~]# cat /etc/redhat-release CentOS release 6.9 (Final) [root@web ~]# uname -a Linux d ...
- Java中的包含义
JAVA提供了强大的应用程序接口,既JAVA类库.他包含大量已经设计好的工具类,帮助程序员进行字符串处理.绘图.数学计算和网络应用等方面的工作.下面简单介绍JAVA核心类库中常用的组建包. 1.jav ...
- 自学Zabbix3.9.2-模板Templates-linking/unlinking
自学Zabbix3.9.2-模板Templates-linking/unlinking HOST链接模板之后,便继承了模板里定义的item,trigger等等,使用这个方法,配置zabbix监控会减少 ...
- 迭代var()内置函数的时候出现RuntimeError: dictionary changed size during iteration的解决办法
下午看了Mr Seven的教学视频,其中有一段讲全局变量的视频,迭代输出全局变量的时候报错了. 视频中的做法: for k,v in vars().items(): print(k) 打印结果 for ...