优化写操作

master
宇天 2019-07-16 15:03:53 +08:00
parent 0c79c47b19
commit d82c4e04b4
4 changed files with 103 additions and 120 deletions

View File

@ -1,23 +1,28 @@
# 1.1.0 / 2018-05-24 # 1.2.0 / 2019-07-16
* [U] 优化结构
* [U] 部分写操作改为异步
* [add] add error log output
* optimize `ls` method # 1.1.0 / 2018-05-24
* rename `this.self` to `this.origin` * [A] 增加异常信息输出
* [U] 优化`ls`API
* [U] 重命名 `this.self``this.origin`
# 1.0.3 / 2017-12-23 # 1.0.3 / 2017-12-23
* [D] 删除异常信息输出
* [del] delete the log output
# 1.0.2 / 2017-11-20 # 1.0.2 / 2017-11-20
* [F] 修复非空目录无法删除的bug
* [fixed] Fixed remove the dir not empty call error.
# 1.0.1 / 2017-04-24 # 1.0.1 / 2017-04-24
* [A] `ls`方法当第2个参数为`true`的时候,可以遍历子目录
* [add] ls function can recur list child folder with second para set to be true.
# 1.0.0 / 2017-02-26 # 1.0.0 / 2017-02-26
* 初始化项目
* new project

View File

@ -1,30 +1,30 @@
![module info](https://nodei.co/npm/iofs.png?downloads=true&downloadRank=true&stars=true) ![module info](https://nodei.co/npm/iofs.png?downloads=true&downloadRank=true&stars=true)
# iofs # iofs
> `iofs` is a bash-like module for reading and writing files on Node.js. It base on Node.js's native `fs` module. > `iofs`是一个基于原生`fs`模块封装的工具, 旨在提供更加方便实用一些常用的API方法(同步), API习惯参考了`bash shell`, 习惯用命令行的朋友, 可能会比较亲切。
## property ## 属性
### self ### origin
> It return the native `fs` module for more requests. > 返回原生的`fs`模块对象, 方便调用一些未封装的额外功能
## API ## APIs
### cat(file) ### .cat(file)
- file `<String>` - file `<String>` 文件路径
> Just like bash's cat, it will read a file and return a Buffer. > 读取文件, 返回一个`Buffer对象`
### ls(path, child) ### .ls(path, recursion)
- path `<String>` - path `<String>`
- child `<Boolean>` - recursion `<Boolean>`
> List all files and folders of the path given exclude '.' and '..'. I t return an array. > 列出指定目录下的所有文件&目录, 不包括 '.' and '..'. 结果返回一个数组.
> If para `child` is set to be ture, it will recur list all files of child dir. > 如果参数`recursion`设为ture, 则会递归遍历所有子目录.
### echo(data, file[, append][, encode]) ### echo(data, file[, append][, encode])
@ -33,16 +33,16 @@
- append `<Boolean>` optional - append `<Boolean>` optional
- encode `<String>` optional - encode `<String>` optional
> Write/Append data to a file. creating the file if it does not yet exist. > 写数据到指定文件中. 如果指定文件不存在, 则自动生成.
> If `append` is set true, it will append data to the file. > 如果`append`设为true, 则往文件后面追加数据, 不会覆盖.
> Default `encode` is utf8. > `encode`为指定编码, 默认utf8.
```javascript ```javascript
let fs = require('iofs') var fs = require('iofs')
fs.echo('hello ', 'test.txt') // replacing test.txt if it exists. fs.echo('hello ', 'test.txt') // 如果test.txt存在, 则覆盖.
fs.echo('world', 'test.txt', true) // append the data to test.txt fs.echo('world', 'test.txt', true) // 不会覆盖, 只会追加到 test.txt中
``` ```
@ -53,11 +53,11 @@ fs.echo('world', 'test.txt', true) // append the data to test.txt
- file `<String>` | `<Buffer>` - file `<String>` | `<Buffer>`
- mode `<Integer>` - mode `<Integer>`
> Changes the mode of the file specified whose pathname is given. > 修改文件&目录的权限.
```javascript ```javascript
fs.chmod('test.txt', 777) // replacing test.txt if it exists. fs.chmod('test.txt', 777)
``` ```
@ -66,7 +66,7 @@ fs.chmod('test.txt', 777) // replacing test.txt if it exists.
- from `<String>` - from `<String>`
- to `<String>` - to `<String>`
> Move a fil to the target location. It can also use to renaming a file. > 移动文件, 支持跨磁盘移动; 同时具备重命名功能。
@ -74,7 +74,7 @@ fs.chmod('test.txt', 777) // replacing test.txt if it exists.
- from `<String>` - from `<String>`
- to `<String>` - to `<String>`
> Copy a fil to the target location. > 复制文件.
@ -82,7 +82,7 @@ fs.chmod('test.txt', 777) // replacing test.txt if it exists.
- path `<String>` - path `<String>`
- recursion `<Boolean>` - recursion `<Boolean>`
> Delete a file or a folder. If path is a folder, `recursion` must be set to true. > 删除文件&目录, 如果要递归删除所以子目录 `recursion`必须设为true.
```javascript ```javascript
@ -97,24 +97,24 @@ fs.rm('./foo', true)
### stat(path) ### stat(path)
- path `<String>` - path `<String>`
> Returns an instance of fs.Stats. > 返回文件的状态信息, 如修改时间, 文件大小等
### isdir(path) ### isdir(path)
- path `<String>` - path `<String>`
> Return true if the path is a folder, and false when it is a file or not yet exists. > 判断指定目录是否为一个目录, 路径不存在或者不是目录都会返回 false.
### mkdir(path) ### mkdir(path)
- path `<String>` - path `<String>`
> Build a folder in where you want. > 创建目录, 可自动创建上级目录(如不存在)
### exists(path) ### exists(path)
- path `<String>` - path `<String>`
> Return true if the path exists, and false not. > 判断文件&目录是否存在

144
index.js
View File

@ -9,10 +9,14 @@
const FS = require('fs') const FS = require('fs')
const PATH = require('path') const PATH = require('path')
class Iofs { const ERROR_FN = (err, res) => {
constructor() { if (err) {
this.origin = FS console.error(err)
} }
}
const Iofs = {
origin: FS,
/** /**
* [cat 文件读取] * [cat 文件读取]
@ -28,32 +32,30 @@ class Iofs {
} }
return null return null
} }
} },
/** /**
* [ls 读取整个目录(不遍历子目录)] * [ls 读取整个目录(不遍历子目录)]
* @param {string} dir [目标路径] * @param {string} dir [目标路径]
* @param {boolean} child [是否遍历子目录] * @param {boolean} recursion [是否递归遍历子目录]
* @return {array} [返回目标目录所有文件名和子目录名, 不包括'.''..'] * @return {array} [返回目标目录所有文件名和子目录名, 不包括'.''..']
*/ */
ls(dir, child) { ls(dir, recursion) {
try { try {
let list = FS.readdirSync(dir) var list = FS.readdirSync(dir)
list = list.map(it => { list.forEach((it, i) => {
return PATH.resolve(dir, it) list[i] = PATH.resolve(dir, it)
}) })
if (!child) { if (recursion) {
return list var tmp = list.concat()
tmp.forEach(it => {
if (this.isdir(it)) {
list = list.concat(this.ls(it, true))
}
})
} }
let tmp = list.concat()
tmp.forEach(it => {
if (this.isdir(it)) {
list = list.concat(this.ls(it, true))
}
})
return list return list
} catch (err) { } catch (err) {
if (err) { if (err) {
@ -61,7 +63,7 @@ class Iofs {
} }
return null return null
} }
} },
/** /**
* [echo 写文件] * [echo 写文件]
@ -75,8 +77,8 @@ class Iofs {
return data return data
} }
let updir = PATH.parse(file).dir var updir = PATH.parse(file).dir
let opt = {} var opt = {}
if (!this.isdir(updir)) { if (!this.isdir(updir)) {
this.mkdir(updir) this.mkdir(updir)
} }
@ -91,29 +93,17 @@ class Iofs {
} }
} }
try { if (!!append) {
if (!!append) { FS.appendFile(file, data, opt, ERROR_FN)
FS.appendFileSync(file, data, opt) } else {
} else { FS.writeFile(file, data, opt, ERROR_FN)
FS.writeFileSync(file, data, opt)
}
} catch (err) {
if (err) {
console.error(err + '')
}
} }
} },
//修改权限 //修改权限
chmod(path, mode) { chmod(path, mode) {
try { FS.chmod(path, mode, ERROR_FN)
FS.chmodSync(path, mode) },
} catch (err) {
if (err) {
console.error(err + '')
}
}
}
/** /**
* [mv 移动文件,兼具重命名功能] * [mv 移动文件,兼具重命名功能]
@ -121,35 +111,35 @@ class Iofs {
* @param {String} target [目标路径/新名] * @param {String} target [目标路径/新名]
*/ */
mv(origin, target) { mv(origin, target) {
let updir = PATH.parse(target).dir var updir = PATH.parse(target).dir
if (!this.isdir(updir)) { if (!this.isdir(updir)) {
this.mkdir(updir) this.mkdir(updir)
} }
try { FS.rename(origin, target, err => {
FS.renameSync(origin, target) if (err) {
} catch (e) { var rs = FS.createReadStream(origin)
let rs = FS.createReadStream(origin) var ws = FS.createWriteStream(target)
let ws = FS.createWriteStream(target)
rs.pipe(ws) rs.pipe(ws)
rs.on('end', err => { rs.on('end', err => {
this.rm(origin) this.rm(origin)
}) })
} }
} })
},
cp(origin, target) { cp(origin, target) {
let updir = PATH.parse(target).dir var updir = PATH.parse(target).dir
if (!this.isdir(updir)) { if (!this.isdir(updir)) {
this.mkdir(updir) this.mkdir(updir)
} }
let rs = FS.createReadStream(origin) var rs = FS.createReadStream(origin)
let ws = FS.createWriteStream(target) var ws = FS.createWriteStream(target)
rs.pipe(ws) rs.pipe(ws)
} },
/** /**
* [rm 删除文件/目录] * [rm 删除文件/目录]
@ -157,22 +147,16 @@ class Iofs {
* @param {[type]} recursion [是否递归删除若删除目录此值须为true] * @param {[type]} recursion [是否递归删除若删除目录此值须为true]
*/ */
rm(origin, recursion) { rm(origin, recursion) {
try { if (recursion) {
if (!!recursion) { var list = this.ls(origin)
let list = this.ls(origin) list.forEach(it => {
list.forEach(it => { this.rm(it, this.isdir(it))
this.rm(it, this.isdir(it)) })
}) FS.rmdir(origin, ERROR_FN)
FS.rmdirSync(origin) } else {
} else { FS.unlink(origin, ERROR_FN)
FS.unlinkSync(origin)
}
} catch (err) {
if (err) {
console.error(err + '')
}
} }
} },
/** /**
* [stat 返回文件/目录的状态信息] * [stat 返回文件/目录的状态信息]
@ -184,7 +168,7 @@ class Iofs {
} catch (err) { } catch (err) {
return null return null
} }
} },
/** /**
* [isdir 判断目标是否为目录] * [isdir 判断目标是否为目录]
@ -196,14 +180,14 @@ class Iofs {
} catch (err) { } catch (err) {
return false return false
} }
} },
/** /**
* [mkdir 新建目录] * [mkdir 新建目录]
* @param {String} dir [目标路径] * @param {String} dir [目标路径]
*/ */
mkdir(dir) { mkdir(dir) {
let updir = PATH.parse(dir).dir var updir = PATH.parse(dir).dir
if (!updir) { if (!updir) {
return return
} }
@ -212,14 +196,8 @@ class Iofs {
this.mkdir(updir) this.mkdir(updir)
} }
try { FS.mkdir(dir, ERROR_FN)
FS.mkdirSync(dir) },
} catch (err) {
if (err) {
console.error(err + '')
}
}
}
/** /**
* [exists 判断目标(文件/目录)是否存在] * [exists 判断目标(文件/目录)是否存在]
@ -230,4 +208,4 @@ class Iofs {
} }
} }
module.exports = new Iofs() module.exports = Iofs

View File

@ -1,6 +1,6 @@
{ {
"name": "iofs", "name": "iofs",
"version": "1.1.0", "version": "1.2.0",
"description": "Base on native fs module, for easy using.", "description": "Base on native fs module, for easy using.",
"main": "index.js", "main": "index.js",
"repository": { "repository": {