-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
109 lines (93 loc) · 2.66 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const fs = require('fs');
const path = require('path');
function hierarchy(obj) {
if (obj.isFile()) return {name: obj.name, type: 'file'}
else return {
name: obj.name,
type: 'dir',
files: obj.files.map((newObj) => {
return newObj.hierarchy()
})
}
}
class fsObject {
constructor() {
this.hierarchy = function() {
return hierarchy(this)
}
}
isDirectory(){
return this instanceof Directory
}
isFile(){
return this instanceof File
}
get relativePath() {
var main = require.main
if (main != undefined) main = main.filename
else main = process.cwd()
return path.relative(path.dirname(main), this.path)
}
}
class Directory extends fsObject {
constructor(dir) {
super()
var main = require.main
if (main != undefined) main = main.filename
else main = process.cwd()
this.path = path.resolve(path.dirname(main), dir)
this.name = path.parse(this.path).base
if (!fs.lstatSync(dir).isDirectory()) throw new Error(`ENOTDIR: '${path.normalize(file)}' is not a directory.`)
}
get files() {
return fs.readdirSync(this.path).map((p) => {
if (fs.lstatSync(path.join(this.path, p)).isDirectory()) return new Directory(path.join(this.path, p))
else return new File(path.join(this.path, p))
})
}
mkDir(name, mode) {
fs.mkdirSync(path.join(this.path, name), mode)
return new Directory(path.join(this.path, name))
}
remove(name) {
if (this.files.find((p) => p.name = name).isDirectory()) fs.rmdirSync(path.join(this.path, name))
else fs.unlinkSync(path.join(this.path, name))
}
delete() {
return fs.rmdirSync(this.path)
}
find(name) {
return this.files.find((p) => p.name == name)
}
create(name) {
fs.closeSync(fs.openSync(path.join(this.path, name), 'wx'))
return new File(path.join(this.path, name))
}
}
class File extends fsObject {
constructor(file) {
super()
var main = require.main
if (main != undefined) main = main.filename
else main = process.cwd()
this.path = path.resolve(path.dirname(main), file)
this.name = path.parse(this.path).base
if (fs.lstatSync(file).isDirectory()) throw new Error(`EISDIR: '${path.normalize(file)}' is a directory.`)
this.read = function(options){ return fs.readFileSync(this.path, options) }
this.write = function(data, options){ return fs.writeFileSync(this.path, data, options) }
}
delete() {
return fs.unlinkSync(this.path)
}
createReadStream(options) {
return fs.createReadStream(this.path, options)
}
createWriteStream(options) {
return fs.createWriteStream(this.path, options)
}
}
module.exports = {
Directory,
File,
fsObject
}