Skip to content

Instantly share code, notes, and snippets.

@ruichuang
Created March 24, 2017 14:50
Show Gist options
  • Save ruichuang/4f6fb237965dc8c4dc0f25865000b838 to your computer and use it in GitHub Desktop.
Save ruichuang/4f6fb237965dc8c4dc0f25865000b838 to your computer and use it in GitHub Desktop.
If this json file won't become too big over the time you should try:
Create a javascript object with the table array in it
var obj = {
table: []
};
Add some data to it like
obj.table.push({id: 1, square:2});
Convert it from an object to string with stringify
var json = JSON.stringify(obj);
use fs to write the file to disk
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
if you want to append it read the json file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
This will work for data big as 100 MB max effectively. Over this limit you should use a database engine.
UPDATE:
Create a function which return the current date (year+month+day) as a string. Create the file named this string + .json.
the fs module has a function which can check for file existance named fs.stat(path, callback). With this you can check if
the file exists. If it exists use the read function if its not use the create function. Use the date string as the path cuz
the file will be named as the today date + .json. the callback will contains a stats object which will be null if the file
does not exists.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment