Home > OS >  How to push data to local JSON file on button click using JavaScript?
How to push data to local JSON file on button click using JavaScript?

Time:07-16

index.html

<button click="submit_data" id="submit">Submit</button>

script.js

document.getElementById('submit').addEventListener('click', function () {
    task = document.getElementById('new_task').value
    task_deadline = document.getElementById('task_deadline').value
    let push_data = {
        "item": task,
        "deadline": task_deadline
    }
    // FileSystem.writeFile("data.json", JSON.stringify(push_data));
})

I have a json file in the same directory and I am trying to push push_data to that file, but I cannot seem to find a solution. I am not using any framework such as Angular or React. Is it possible using plain javascript? If not, what are the possible solutions?

CodePudding user response:

You just need to use the API designed for this purposes

https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API#writing_to_files

async function saveFile(blob) {
  // create a new handle
  const newHandle = await window.showSaveFilePicker();
  // create a FileSystemWritableFileStream to write to
  const writableStream = await newHandle.createWritable();
  // write our file
  await writableStream.write(blob);
  // close the file and write the contents to disk.
  await writableStream.close();
}

function save () {
    let push_data = {
        "item": "test",
        "deadline": "test2"
    }
    saveFile(JSON.stringify(push_data)).then(console.log).catch(console.error); 
}

save();

Note:

This API opens up potential functionality the web has been lacking. Still, security has been of utmost concern when designing the API, and access to file/directory data is disallowed unless the user specifically permits it.

CodePudding user response:

You can create a URL to download. A dataURL. See also working fiddle

var storageObj = {
  "hello": "world"
}

function download_json() {
  var dataStr = "data:text/json;charset=utf-8,"   encodeURIComponent(JSON.stringify(storageObj));
  var dlAnchorElem = document.querySelector('.dummy');
  dlAnchorElem.setAttribute("href", dataStr);
  dlAnchorElem.setAttribute("download", "scene.json");
  dlAnchorElem.click();
}
Click to download JSON on a non-sandbox environment 
<form onsubmit="download_json(); return false">
  <button click="submit_data" id="submit">Submit</button>
</form>

<a ></a>

  • Related