NeutralinoJS storage

658 views Asked by At

This is NeutralinoJS storage API for writing JSON. Is it possible to update JSON file (push data), not just overwrite data with new JS object. How to do that?

    // Javascript Object to be stored as JSON
let data = { 
    bucket : 'test', 
    content : { 
            item : 10 
    } 
}
// stores the data into JSON based data store.           
Neutralino.storage.putData(data,

// executes on successful storage of data
    function () {
    console.log('Data saved to storage/test.json');

    },
// executes if an error occurs

    function () {
    console.log('An error occured while saving the Data');

    }
);
1

There are 1 answers

1
Aditya On

The Neutralino.storage api takes string instead of JSON to save into local storage.

And you can create your JavaScript Objects to String Very easily, for example:

const myUser = {
  name: "John Doe",
  age: 19,
  married: false
}

const myUserString = JSON.stringify(myUser);
console.log(myUserString); // {"name":"John Doe","age":19,"married":false}

Here you can see how we used JSON.stringify method to convert our JavaScript Object into string.

Now We Can Also Convert generated string back to our javascript object, example:

const myUserString = '{"name":"John Doe","age":19,"married":false}';
const myUser = JSON.parse(myUserString);
console.log(myUser);

So now we can easily store our Objects and arrays to local storage and easily modify them, example:

async function saveToStorage(myUser) {
  let myUserString = JSON.stringify(myUser);
  await Neutralino.storage.setData('myUser', myUserString);
});

async function loadFromStorage() {
  let myUserString = await Neutralino.storage.getData('myUser');
  let myUser = JSON.parse(myUserString);
  return myUser;
}

saveToStorage({
  name: "John Doe",
  age: 19,
  married: false
}).then(async () => {
  let myUser = await loadFromStorage();
  myUser.name = "Jane Doe"
  await saveToStorage(myUser);
});