@steinerjing/gutterball
v1.0.4
Published
Utilities without bumpers
Downloads
5
Maintainers
Readme
GutterBall
An amazong collection of one utility.
Utilities:
- FileActor
- <end of list>
FileActor
Provides a handy function to persists data by reading from and writing to a JSON file in only a one or few lines of code.
Import
ESM
import { fileActor } from '@steinerjing/gutterball'
CJS
const { fileActor } = require('@steinerjing/gutterball')
Reading Data
The following is a shorthand way to read all data from the JSON file.
const allData = fileActor('./data/counters.json', data => data)
To get more specific data, create a seperate object and return it in the callback. This example returns an array of all users with admin rights:
const allData = fileActor('./data/counters.json', data => {
return data.users.filter( user => user.isAdmin )
})
Changing Data
To change persistant data, make changes to the data parameter in the callback. Note that you can not change the data object itself because it is the arguemnt, but you can change any attribute about the data. The changes will persist automatically.
The following example gives all users admin rights:
fileActor('./data/counters.json', data => {
data.users.forEach( user => user.isAdmin === true )
})
Reading and Changing Data
Reading and changing data can both take place in the callback. As an example, the following gives all users admin rights and returns the number of total users.
fileActor('./data/counters.json', data => {
data.users.forEach( user => user.isAdmin === true )
return data.users.length
})
The following example increases a counter and returns the pervious counter value each time it is called. The changes are stored in the JSON file provided by the first argument. If the file doesn't exist is will be created. The data stored in the JSON file must contain an object as the root, not an array.
const newID = fileActor('./data/counters.json', data => data.nextMessageID++)