-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (89 loc) · 2.85 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
import { get, set } from "idb-keyval";
export const hasFileSystemAccess = () => !!window || !!window.showOpenFilePicker;
// Language: javascript
export async function getFile(options = {}) {
if (hasFileSystemAccess()) {
const [fileHandle] = await window.showOpenFilePicker(options);
return file(fileHandle);
}
}
export const file = async (fileHandle) => {
const file = await fileHandle.getFile();
return {
// fileHandle,
name: fileHandle.name,
kind: fileHandle.kind,
size: file.size,
lastModified: file.lastModified,
lastModifiedDate: file.lastModifiedDate,
text: () => {
return file.text();
},
stream: () => {
return file.stream();
},
arrayBuffer: () => {
return file.arrayBuffer();
},
// writeIn is to allow the user to write in the file
write: async (data) => {
// await stream . write({ type: "write", position: position, data: data })
const writableStream = await fileHandle.createWritable();
await writableStream.write(data);
await writableStream.close();
},
seek: async (position) => {
const writableStream = await fileHandle.createWritable();
await writableStream.seek(position);
await writableStream.close();
},
truncate: async (size) => {
const writableStream = await fileHandle.createWritable();
await writableStream.truncate(size);
await writableStream.close();
},
};
};
//create a file
export async function createFile(options = {}) {
let opt = {
types: [
{
description: "Text Files",
accept: {
"text/plain": [".txt"],
},
},
],
...options,
};
if (hasFileSystemAccess()) {
const fileHandle = await window.showSaveFilePicker(opt);
// const file = await fileHandle.createFile();
return file(fileHandle);
}
}
export async function getDirectories(options = {}) {
if (hasFileSystemAccess()) {
const dirHandle = await window.showDirectoryPicker();
const promises = await folder(dirHandle).then((data) => {
console.log(data);
}).catch((err) => {
});;
// console.log(promises);
return promises;
}
}
const folder = async (dirHandle) => {
const promises = [];
for await (const entry of dirHandle.values()) {
if (entry.kind !== "file") {
let p = { name: entry.name, dir: await folder(entry) };
promises.push(p);
} else {
// promises.push(getFile(entry));
promises.push(entry.name);
}
}
return { name: dirHandle.name, dir: promises };
};