Open file from local system and save changes to file that opened

In this code we will be learn how to use The File System Access API to open file from local system and save changes to file that opened,
in this example we are try with txt file:
<button onclick="openfile()" title="Open txt file">Openfile</button>
<button onclick="savefile()" title="Open txt file">Save file</button>
<textarea id="editor" style="width: 100%; height: 200px;" placeholder="open file..."></textarea>

<script>
let editor = document.getElementById("editor");

const openfile = async () => {
[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();
editor.value = contents;

}

const savefile = async () => {

const writable = await fileHandle.createWritable();
await writable.write(editor.value);
await writable.close();
}




</script>
to save changes with keybord event Ctrl + s add this code as follows:
window.addEventListener("keydown" , e => {
if (e.key === 's' && e.metaKey) {
    e.preventDefault();
    savefile();
}

});

return to first exemple:
let editor = document.getElementById("editor");

const openfile = async () => {
    [fileHandle] = await window.showOpenFilePicker();
  const file = await fileHandle.getFile();
  const contents = await file.text();
  editor.value = contents;

}

const savefile = async () => {
 
  const writable = await fileHandle.createWritable();
  await writable.write(editor.value);
  await writable.close();
}
window.addEventListener("keydown" , e => {
if (e.key === 's' && e.metaKey) {
    e.preventDefault();
    savefile();
}

});


Open file from local system and save changes to file that opened,

© 2025 Manajmnt code

Share to :

Related

Comments