-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathfile.node.ts
215 lines (171 loc) · 5.87 KB
/
file.node.ts
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
namespace $ {
function stat_convert(stat: ReturnType<typeof $node.fs.statSync>): null | $mol_file_stat {
if( !stat ) return null
let type: $mol_file_type | undefined
if (stat.isDirectory()) type = 'dir'
if (stat.isFile()) type = 'file'
if (stat.isSymbolicLink()) type = 'link'
if (! type) return $mol_fail( new Error(`Unsupported file type`) )
return {
type,
size: Number(stat.size),
atime: stat.atime,
mtime: stat.mtime,
ctime: stat.ctime
}
}
export function $mol_file_node_buffer_normalize(buf: Buffer< ArrayBuffer >): Uint8Array< ArrayBuffer > {
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
}
export class $mol_file_node extends $mol_file {
static relative<This extends typeof $mol_file>(this: This, path : string ) {
return this.absolute<This>( $node.path.resolve( this.base, path ).replace( /\\/g , '/' ) )
}
@ $mol_mem
override watcher(reset?: null) {
const path = this.path()
const root = this.root()
// Если папки/файла нет, watch упадет с ошибкой
// exists обратится к parent.version и parent.watcher
// Поэтому у root-папки и выше не надо вызывать exists, иначе поднимется выше base до корня диска
// exists вызывать надо, что б пересоздавать вотчер при появлении папки или файла
if (! root && ! this.exists() ) return super.watcher()
let watcher
try {
// Между exists и watch файл может удалиться, в любом случае надо обрабатывать ENOENT
watcher = $node.fs.watch( path )
} catch (error: any) {
if ( ! (error instanceof Error) ) error = new Error('Unknown watch error', {cause: error})
error.message += '\n' + path
if ( root || error.code !== 'ENOENT' ) {
this.$.$mol_fail_log(error)
}
// Если файла нет - вотчер не создается, создастся потом, когда exists поменяется на true.
// Если создание упало с другой ошибкой - не ломаем работу mol_file, деградируем до не реактивной fs.
return super.watcher()
}
watcher.on('change', (type: 'change' | 'rename', name) => {
if (! name) return
const path = $node.path.join( this.path(), name.toString() )
;(this.constructor as typeof $mol_file_base).changed_add(type, path)
})
watcher.on('error', e => this.$.$mol_fail_log(e) )
let destructed = false
watcher.on('close', () => {
// Если в процессе работы вотчер сам закрылся, надо его переоткрыть
if (! destructed) setTimeout(() => $mol_wire_async(this).watcher(null), 500)
})
return {
destructor() {
destructed = true
watcher.close()
}
}
}
@ $mol_action
protected override info( path: string ) {
try {
return stat_convert($node.fs.statSync(path))
} catch( error: any ) {
if (this.$.$mol_fail_catch(error)) {
if (error.code === 'ENOENT') return null
error.message += '\n' + path
this.$.$mol_fail_hidden(error)
}
}
return null
}
@ $mol_action
protected override ensure() {
const path = this.path()
try {
$node.fs.mkdirSync( path, { recursive: true } )
return null
} catch( e: any ) {
if (this.$.$mol_fail_catch(e)) {
if (e.code === 'EEXIST') return null
e.message += '\n' + path
this.$.$mol_fail_hidden(e)
}
}
}
@ $mol_action
protected override copy(to: string) {
$node.fs.copyFileSync(this.path(), to)
}
@ $mol_action
protected override drop() {
$node.fs.unlinkSync( this.path() )
}
@ $mol_action
protected override read() {
const path = this.path()
try {
return $mol_file_node_buffer_normalize($node.fs.readFileSync( path ) as Buffer< ArrayBuffer >)
} catch( error: any ) {
if (! $mol_promise_like(error)) {
error.message += '\n' + path
}
$mol_fail_hidden( error )
}
}
@ $mol_action
protected override write(buffer: Uint8Array) {
const path = this.path()
try {
$node.fs.writeFileSync( path, buffer )
} catch( error: any ) {
if (this.$.$mol_fail_catch(error)) {
error.message += '\n' + path
}
return this.$.$mol_fail_hidden( error )
}
}
protected override kids() {
const path = this.path()
try {
const kids = $node.fs.readdirSync( path )
.filter( name => !/^\.+$/.test( name ) )
.map( name => this.resolve( name ) )
return kids
} catch( e: any ) {
if (this.$.$mol_fail_catch(e)) {
if (e.code === 'ENOENT') return []
e.message += '\n' + path
}
$mol_fail_hidden(e)
}
}
override resolve( path : string ) {
return ( this.constructor as typeof $mol_file )
.relative( $node.path.join( this.path() , path ) ) as this
}
override relate( base = ( this.constructor as typeof $mol_file ).relative( '.' )) {
return $node.path.relative( base.path() , this.path() ).replace( /\\/g , '/' )
}
@ $mol_mem_key
override readable(opts: { start?: number, end?: number }) {
const { Readable } = $node['node:stream'] as typeof import('stream')
const stream = $node.fs.createReadStream(this.path(), {
flags: 'r',
autoClose: true,
start: opts?.start,
end: opts?.end,
encoding: 'binary',
})
return Readable.toWeb(stream) as ReadableStream<Uint8Array<ArrayBuffer>>
}
@ $mol_mem
override writable(opts?: { start?: number }) {
const { Writable } = $node['node:stream'] as typeof import('stream')
const stream = $node.fs.createWriteStream(this.path(), {
flags: 'w+',
autoClose: true,
start: opts?.start,
encoding: 'binary',
})
return Writable.toWeb(stream) as WritableStream<Uint8Array<ArrayBuffer>>
}
}
$.$mol_file = $mol_file_node
}