/
fileUtils.ts
327 lines (292 loc) · 8.83 KB
/
fileUtils.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { deepClone } from '__gUtils/busiUtils';
const path = require("path");
const fse = require('fs-extra');
const csv = require("fast-csv");
declare global {
interface Window {
fileId: number;
}
}
export {}
interface FileIds {
file: any[];
folder: any[];
}
interface FileData {
id: number;
parentId: number;
isDir: boolean;
name: string;
ext: string;
filePath: string;
children: FileIds;
stats: object;
root: boolean;
open: boolean;
}
interface FileTreeByPath {
ids: FileIds;
fileTree: any;
}
interface FileInputData extends FileData {
[propName: string]: any;
}
export const listDir = (filePath: string): Promise<any[]> => {
return new Promise((resolve, reject) => {
fse.readdir(filePath, (err: Error, files: any[]) => {
if(err) {
reject(err)
return;
}
resolve(files)
})
})
}
export const statSync = (filePath: string): any => {
return fse.statSync(filePath)
}
export const getTreeByFilePath = (strategy: FileData, fileTree: any): Promise<FileTreeByPath> => {
fileTree = fileTree || {};
let strategyPath: string = strategy.filePath;
strategyPath = path.normalize(strategyPath)
const filePath: string = path.resolve(strategyPath);
let dirList: any[] = [];
let fileList: any[] = [];
let ids: FileIds = { file: [], folder: [] };
const ignoreList = ['.git', '.DS_Store']
return new Promise((resolve, reject) => {
listDir(filePath).then(files => {
files.forEach((file: any) => {
if(ignoreList.indexOf(file) !== -1) return;
const fileDir: string = path.join(filePath, file);
const stats: any = fse.statSync(fileDir)
if(stats){
const isDir: boolean = stats.isDirectory();
const fileInfo: FileData = buildFileObj({
id: 0,
parentId: strategy.id,
isDir,
name: file,
ext: path.extname(fileDir).slice(path.extname(fileDir).indexOf('.') + 1),
filePath: fileDir,
children: {
folder: [],
file: []
},
stats,
root: false,
open: false
})
//保证顺序
if(isDir){
dirList.push(fileInfo)
}else{
fileList.push(fileInfo)
}
}
})
dirList.forEach((dir: FileData): void => {
const id: number = window.fileId++
ids.folder.push(id);
fileTree[id] = {
...dir,
id
}
})
fileList.forEach((file: FileData): void => {
const id: number = window.fileId++
ids.file.push(id);
fileTree[id] = {
...file,
id
}
})
resolve({ ids, fileTree })
})
// .catch(err => reject(err))
})
}
//清空children
export const clearChildrenByFileId = (fileTree: any, fileId: number): any => {
const target: any = fileTree[fileId]
const children: any = target.children;
const files: any = children['file'] || [];
const folders: any = children['folders'] || [];
[...files, ...folders].forEach(id => {
fileTree[id] = null
delete fileTree[id]
})
target.children = {
file: [],
folder: []
}
return fileTree
}
//建立fileObj
export const buildFileObj = (fileData: FileInputData): FileData => {
const {
id,
isDir,
name,
ext,
filePath,
children,
stats,
root,
open,
parentId,
} = fileData;
return {
id,
isDir,
name,
ext,
filePath,
children,
stats,
root,
open,
parentId
}
}
//打开文件树
/**
* @param {object} folder
* @param {object} oldFileTree
* @param {boolean} openStatus
* @param {boolean} force 强制清空
*/
export const openFolder = (store: any, folder: FileData, oldFileTree: any, openStatus?: boolean, force?: boolean): Promise<{}> => {
oldFileTree = deepClone(oldFileTree);
//清空
if(force) oldFileTree = clearChildrenByFileId(oldFileTree, folder.id);
return new Promise(async (resolve) => {
if(openStatus === undefined){
openStatus = !folder.open
}
if(openStatus){
const { ids, fileTree }: FileTreeByPath = await getTreeByFilePath(folder, oldFileTree)
store.dispatch('setFileTree', fileTree)
store.dispatch('setFileNode', {id: folder.id, attr: 'children', val: ids})
resolve(fileTree)
}else{
resolve({})
}
//打开
store.dispatch('setFileNode', {id: folder.id, attr: 'open', val: openStatus})
})
}
//添加文件
export const addFile = (parentDir = "", filename: string, type: string): void => {
let targetPath: string;
if(!parentDir) targetPath = filename;
else targetPath = path.join(parentDir, filename)
targetPath = path.normalize(targetPath)
if(type === 'folder'){
fse.ensureDirSync(targetPath)
}else{
fse.ensureFileSync(targetPath)
}
}
//更改文件名
export const editFileFolderName = (oldPath: string, newPath: string): Promise<{}> => {
oldPath = path.normalize(oldPath)
newPath = path.normalize(newPath)
return new Promise((resolve, reject) => {
fse.rename(oldPath, newPath, (err: Error) => {
if(err){
console.error(err)
reject(err)
return
}
resolve({})
})
})
}
//删除文件或
export const removeFileFolder = (targetPath: string): Promise<void> => {
targetPath = path.normalize(targetPath)
return new Promise(resolve => {
if(!fse.existsSync(targetPath)) {
resolve()
return
}
fse.removeSync(targetPath)
resolve()
})
}
export const removeFilesInFolder = (targetDir: string) => {
targetDir = path.normalize(targetDir)
if(!fse.existsSync(targetDir)) throw new Error(`${targetDir} not existed!`)
const promises = fse.readdirSync(targetDir).map((file: any) => {
const filePath = path.join(targetDir, file)
return removeFileFolder(filePath)
});
return Promise.all(promises)
}
//获取文件内容
export const getCodeText = (targetPath: string): Promise<string> => {
if(!targetPath) throw new Error('文件路径不存在!')
targetPath = path.normalize(targetPath)
return new Promise((resolve, reject): void => {
fse.readFile(targetPath, (err: Error, data: any) => {
if(err){
console.error(err)
reject(err)
return;
}
resolve(data.toString())
})
})
}
//写入文件
export const writeFile = (filePath: string, data: string): Promise<void> => {
filePath = path.normalize(filePath)
return new Promise((resolve, reject) => {
if(data === undefined) reject(new Error('input data is undefined!'))
fse.outputFile(filePath, data, (err: Error): void => {
if(err){
console.error(err)
reject(err)
return;
}
resolve()
})
})
}
export const writeCSV = (filePath: string, data: string): Promise<void> => {
filePath = path.normalize(filePath)
return new Promise((resolve) => {
csv.writeToPath(filePath, data, {
headers: true,
}).on("finish", function(){
resolve()
})
})
}
//清空文件内容
export const clearFileContent = (filePath: string): Promise<any> => {
filePath = path.normalize(filePath)
return new Promise((resolve, reject) => {
fse.outputFile(filePath, '', (err: Error, data: any): void => {
if(err){
reject(err);
return;
}
resolve(data)
})
})
}
export const existsSync = (filePath: string): boolean => {
return fse.existsSync(filePath)
}
export const copySync = (fromPath: string, toPath: string): void => {
fse.copySync(fromPath, toPath)
}
export const readJsonSync = (jsonPath: string): {} => {
return fse.readJsonSync(jsonPath)
}
export const outputJson = (jsonPath: string, json: {}): void => {
return fse.outputJson(jsonPath, json)
.catch((err: Error) => console.error(err))
}