-
Notifications
You must be signed in to change notification settings - Fork 0
/
Folder.js
72 lines (69 loc) · 2 KB
/
Folder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const fs = require("fs")
const path = require("path")
const pFs = fs.promises
const readdir = async (folder)=>{
return new Promise((resolve, reject)=>{
fs.readdir(folder, (err, files) => {
if(err) return reject(err)
resolve(files)
})
})
}
const rmdir = async folder => {
return new Promise((resolve, reject)=>{
fs.rmdir(folder, err => {
if(err) return reject(err)
resolve()
})
})
}
const Folder = {
async read(folder, delegate){
delegate = delegate || async function(filePath){return filePath}
let files = await readdir(folder)
let justFiles = []
let upper = files.length
for(let i = 0; i < upper; i++){
let f = path.join(folder, files[i])
let handle = null
let stat = null
try{
handle = await pFs.open(f, "r")
stat = await handle.stat()
}catch(e){
console.error(e)
} finally {
if(handle) handle.close()
}
if(stat && stat.isDirectory()){
justFiles = justFiles.concat(await Folder.read(f))
} else {
justFiles.push(await delegate(f))
}
}
return justFiles
},
async delete(folderPathName){
let files = await this.read(folderPathName)
let upper = files.length
for(let i = 0; i < upper; i++){
await File.unlink(files[i])
}
let folders = await readdir(folderPathName)
let foldersMax = folders.length
for(let i = 0; i < foldersMax; i++){
try{
await rmdir(`${folderPathName}/${folders[i]}`)
}catch(e){console.log(e)}
}
},
async create(folder){
return new Promise((resolve, reject)=>{
fs.mkdir(folder, (err)=>{
if(err) return reject(err)
resolve(folder)
})
})
}
}
module.exports = Folder