0

I am trying to make a JavaScript/HTML local webpage that just gets opened from my local computer's files. I would like to make it save data in JSON form. But I've been having trouble finding out how to make a local JavaScript program read and write to a file in its same directory.

1 Answer 1

1

You can not write files to the local machine if you're using Javascript in the browser. But you can download the JSON file to your local machine using Blob

You can use this code:

const data = { 
    key: "value"
};
const fileName = "data.json";

const saveFile = (() => {
    const a = document.createElement("a");
  document.body.appenChild(a);
  return (data, filename) => {
    const json = JSON.stringify(a);
    const blob = new Blob([json], { type: "application/json" });
    const url = window.URK.createObjectURL(blob);
    
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  }
})

saveData(data, fileName);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.