Skip to content

Instantly share code, notes, and snippets.

@ndrean
Last active July 2, 2023 18:44
Show Gist options
  • Save ndrean/d5314fd88d0cc25d2fd7631bffbbda0b to your computer and use it in GitHub Desktop.
Save ndrean/d5314fd88d0cc25d2fd7631bffbbda0b to your computer and use it in GitHub Desktop.
Open file from browser, XML parse it, serialize it and save to disk
<body>
<input id="input" type="file" accept=".gpx" />;
<script type="module" src="/main.js"></script>
</body>
let newHandle;
input.addEventListener("change", async (e) => {
newHandle = await window.showSaveFilePicker({
suggestedName: "yetcleaned.gpx",
types: [
{
description: "Text documents",
accept: {
"text/plain": [".gpx"],
},
},
],
});
read(e);
});
async function read(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.addEventListener("load", async () => {
return new Promise((resolve) => {
const doc = new DOMParser().parseFromString(reader.result, "text/xml");
[...doc.documentElement.querySelectorAll("PostalCode")].forEach(
(node) => {
node.textContent = Number(node.textContent.replace(" ", ""));
}
);
resolve(new XMLSerializer().serializeToString(doc));
}).then(async (string) => await saveToFile(string));
});
}
async function saveToFile(string) {
try {
const writableStream = await newHandle.createWritable();
await writableStream.write(string);
await writableStream.close();
} catch (err) {
console.log(err);
}
}
@ndrean
Copy link
Author

ndrean commented Jul 2, 2023

https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML

https://developer.chrome.com/articles/file-system-access/

"Sometimes processing the to-be-saved data takes some time after the user clicks the Save button in your app. A common gotcha is to do this work before the showSaveFilePicker() code has run, resulting in a SecurityError Failed to execute 'showSaveFilePicker' on 'Window': Must be handling a user gesture to show a file picker.. Instead, get the file handle first, and only after obtaining the file handle start processing the data."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment