How can I save a json value from HTML/JavaScript in a json file locally without plugin?

I want to save some numbers from a small program in a local JSON file.

Example:

const increaseButton = document.getElementById("increase-button")
const numberField = document.getElementById("count-field")
let myNum = 0
let myArray = []
increaseButton.addEventListener("click", increaseNum)

function increaseNum() {
    myNum++
    numberField.innerText = myNum
    myArray.pop()
    myArray.push(myNum)
    let jsonString = JSON.stringify(Object.assign({}, myArray))
    console.log(jsonString)
}

The jsonString should be saved in a local file “myjson.json”.

Goal: If I increase the number with the increaseButton, the new value should be saved in the “myjson.json” file:

{
    "numbers": {
        "0":1}
}

The only option I found was with node.js plugin “fs” and a lot of code. Couldn’t it be easier?

Hello!

No, it can’t be done with a file if you want to save it locally. You could, however, save it to the localStorage:

// To save
localStorage.setItem('numbers', jsonString)

// To read
const jsonString = localStorage.getItem('numbers') || '';
const obj = JSON.parse(jsonString);
3 Likes

Thanks!

When I restart the browser is the value saved?

At the top of my head I’d think you could either create a upload/download option thus manually handle the file.
OR you could turn the data into a cookie and save it in the browser that way.

I think browsers in general are a bit iffy about just writing and reading files on the computer without explicit control of the user. You know, because of malware.

3 Likes

Sounds sensible but FCC is storing data in ls (and all the rest), at least I can access it from the console or from storage tab, and don’t remember them asking…

@BigBang localStorage seems to be persistent if you close the page. If using incognito mode it doesn’t though.

sessionStorage instead, disappears when page is closed.

Edit: also this mdn tutorial seems good start

2 Likes

Yes if you save it in the local storage, it would remain there unless you delete it.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.