Skip to content

Instantly share code, notes, and snippets.

@naosim
Last active October 31, 2021 06:31
Show Gist options
  • Save naosim/000bb3c6acc25078131471d73253996e to your computer and use it in GitHub Desktop.
Save naosim/000bb3c6acc25078131471d73253996e to your computer and use it in GitHub Desktop.
FileSystemAccessAPIを使ってJSONの読み書きをする
class LocalFileJsonRepository {
constructor(fileHandle = null) {
this.fileHandle = fileHandle;
}
async init() {
if(this.fileHandle) {
return;
}
[this.fileHandle] = await window.showOpenFilePicker();
}
async load() {
const file = await this.fileHandle.getFile();
const text = await file.text();
return JSON.parse(text);
}
async save(obj) {
const writable = await this.fileHandle.createWritable();
await writable.write(JSON.stringify(obj));
await writable.close();
}
close() {
this.fileHandle = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment