Issue
I have a html form and I want to create a json-file with data introduced in html fields.
Right now, it is visible in console json-text but it doesn't create a new json-file with this content.
Also,I have an error, Uncaught ReferenceError: require is not defined.
// get the form element from dom
const formElement = document.querySelector('form#forms')
// convert the form to JSON
const getFormJSON = (form) => {
const data = new FormData(form);
return Array.from(data.keys()).reduce((result, key) => {
if (result[key]) {
result[key] = data.getAll(key)
return result
}
result[key] = data.get(key);
return result;
}, {});
};
// handle the form submission event, prevent default form behaviour, check validity, convert form to JSON
const handler = (event) => {
event.preventDefault();
const valid = formElement.reportValidity();
if (valid) {
const result = getFormJSON(formElement);
// handle one, multiple or no files uploaded
const images = [result.images].flat().filter((file) => !!file.name)
// handle one, multiple or no languages selected
const languages = [result.languages || []].flat();
// convert the checkbox to a boolean
const isHappyReader = !!(result.isHappyReader && result.isHappyReader === 'on')
// use spread function, but override the keys we've made changes to
const output = {
...result,
images,
languages,
isHappyReader
}
console.log(output)
}
}
formElement.addEventListener("submit", handler)
const fs = require('fs');
const dataNew = JSON.stringify(output);
fs.writeFile('output.json', dataNew, (err) => {
if (err) {
console.log("error")
throw err;
}
console.log("JSON data is saved.");
});
</script>
</body>
Solution
It seems you are on the frontend. You can't write files like this because of security. This would result in every website with some JavaScript being potentially able to write files to your system and you really don't want that.
Additionally fs
is a Node API that is not available in the browser.
One option would be to download the JSON file from the frontend which you could do using the following code:
/**
* Download a JSON file.
* @param {sting} filename filename
* @param {any} obj any serializeable object
*/
function downloadJson(filename, obj) {
// serialize to JSON and pretty print with indent of 4
const text = JSON.stringify(obj, null, 4);
// create anchor tag
var element = document.createElement("a");
element.setAttribute(
"href",
"data:application/json;charset=utf-8," + encodeURIComponent(text)
);
element.setAttribute("download", filename);
// don't display the tag
element.style.display = "none";
// add tag to document
document.body.appendChild(element);
// click it: this starts the download
element.click();
// remove the tag again
document.body.removeChild(element);
}
window.addEventListener("DOMContentLoaded", (event) => {
// Start file download.
downloadJson("helloWorld.json", { hello: "World" });
});
If you add that to your page the save dialog will appear on a user's system. Here the one I am getting on Ubuntu:
And here the content of the downloaded file:
Please read this thread on the pros and cons of using an approach like this.
Answered By - Mushroomator
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.