Skip to content

Instantly share code, notes, and snippets.

@okumurakengo
Last active October 18, 2021 08:41
Show Gist options
  • Save okumurakengo/493a722348269535d6803039831f6b32 to your computer and use it in GitHub Desktop.
Save okumurakengo/493a722348269535d6803039831f6b32 to your computer and use it in GitHub Desktop.
Native File System API Test
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>aa</h1>
<button id="butOpenFile">butOpenFile</button>
<button id="butDirectory">butDirectory</button>
<script>
// 参考:https://developers.google.com/web/updates/2019/08/native-file-system
let fileHandle;
butOpenFile.addEventListener('click', async (e) => {
fileHandle = await window.chooseFileSystemEntries();
const file = await fileHandle.getFile();
const contents = await file.text();
console.log(contents)
// Do something with the file handle
});
function getNewFileHandle() {
const opts = {
type: 'saveFile',
accepts: [{
description: 'Text file',
extensions: ['txt'],
mimeTypes: ['text/plain'],
}],
};
const handle = window.chooseFileSystemEntries(opts);
return handle;
}
async function writeFile(fileHandle, contents) {
// Create a writer (request permission if necessary).
const writer = await fileHandle.createWriter();
// Make sure we start with an empty file
await writer.truncate(0);
// Write the full length of the contents
await writer.write(0, contents);
// Close the file and write the contents to disk
await writer.close();
}
// (async () =>
// writeFile(await getNewFileHandle(), "aaa")
// )()
const butDir = document.getElementById('butDirectory');
butDir.addEventListener('click', async (e) => {
const opts = {type: 'openDirectory'};
const handle = await window.chooseFileSystemEntries(opts);
const entries = await handle.getEntries();
for await (const entry of entries) {
const kind = entry.isFile ? 'File' : 'Directory';
console.log(kind, entry.name);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment