First of all, I have created another node module 5 years ago, so this is not my first time. I published it because I can. This one isn't that different... but, let me tell the story.
Package name: 'jsonian'
version: '0.0.2'
// I had to correct the readme, otherwise it is same as 0.0.1
So what does it do?
It lets you persist javascript object to a json file.
...Am I getting Eyeballs yet?
Yeah, there are bunch of other modules that let you do it. I didn't like the way they expose the api. Most ones I found use a getter/setter approach.
Nothing wrong with that, may be it is even better for certain application.
I am working on a jupyter notebook and I wanted a way to keep my js objects and json files to be in sync without changing the syntax too much.
I'll share a bit of Readme.md
here
Usage
const jsonian = require('jsonian');
const $table = jsonian('./testTable.json'); // file must already exist
$table
is proxy to a root object. You can use it to get or set values as with a usual object.
// './testTable.json'
{
"name": "Students"
}
// to read value
var name = $table.name; // "Students"
// to write value to file
$table.name = "New_table_name"; // replaces "Students" in file './testTable.json'
$table.rows = ["name","class"]; // adds new field "rows" in file './testTable.json'
The
$
sign in the begining of$table
is an indicator that it is a pure json object (jsonian proxy). I find it useful, to maintain a readable code. If you already use $ for something else feel free to come up with your own convention.
That is it. Your object will always be persisted in file.
The uglys
It is using javascript Proxy object to capture get/set actions. So assume all the gotchas associated with it.
The project is still in an alpha state. It is untested for the most part.
This is particularly not recommended for web servers (scalability won't be great with this kind of file write load + I can't think of any usecases) and browsers as long as they don't have filesystem access.
The good part is it all sits in 31 lines of index.js
.
If you read this far, I think I've earned the right to share git repo https://github.com/bwowsersource/jsonian
Ok how does it work?
When we load a file, it reads the file and parse json to a rootObj
.
The loader then creates a Proxy
around this rootObj
. The proxy intercepts get
and set
operations on rootObj
.
set
s will trigger a JSON.stringify
of rootObj
followed by a write-to-file.
On the other hand get
will return the value on rootObject
only if it is not an object
. If the value being accessed is another object, it will create another proxy around this child object, thus allowing trapping of nested objects.
Top comments (0)