Created
September 14, 2016 03:36
-
-
Save ncwhale/b42e50733d0c6eb43c856d6bae385b2b to your computer and use it in GitHub Desktop.
Promise 玩递归喵~
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* Promised fs - fs.js | |
* Copyright(c) 2016 | |
* MIT Licensed | |
* | |
* @author Whale Mo (@whalemo) | |
*/ | |
const fs = require('fs'); | |
const Path = require('path'); | |
const Promise = require('bluebird'); | |
let promised_fs = Promise.promisifyAll(fs, { | |
suffix: "Promise" | |
}); | |
// 假定传入的是文件夹名字,以此展开递归删除操作 | |
promised_fs['rmdirr'] = (path) => { | |
return promised_fs | |
.readdirPromise(path) | |
.catch(err => { | |
// 不是文件夹,直接删除即可 | |
if (err.code === 'ENOTDIR') { | |
return promised_fs.slient_unlink(path); | |
} | |
// 不存在的文件,不是错误,直接返回即可 | |
if (err.code === 'ENOENT') { return; } | |
throw err; | |
}).then(files => { | |
// 空文件夹,没有文件,不用处理继续下一步即可。 | |
if (files == null || files == undefined) { | |
return; | |
} | |
return Promise.map(files, file => { | |
let file_path = Path.join(path, file); | |
return promised_fs.unlinkPromise(file_path) | |
.catch(err => { | |
// 对于子文件夹,递归删除 | |
if (err.code === 'EISDIR') { | |
return promised_fs.rmdirr(file_path); | |
} | |
// 不存在,可能并发了,不过达到目的了,所以不是错误 | |
if (err.code === 'ENOENT') { return; } | |
throw err; | |
}); | |
}, { concurrency: 3 }); | |
}).then(_ => { | |
return promised_fs.rmdirPromise(path) | |
.catch(err => { | |
// 不存在,可能并发了,不过达到目的了,所以不是错误 | |
if (err.code === 'ENOENT') { return; } | |
throw err; | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment