node-little-db
is a third-party Node.js library that helps you synchronize object content to a file. Its principle is simple: when you change the content of an object, it automatically calls fs.writeFileSync()
to write the object content to a file.
Install node-little-db
using the following command:
npm i node-little-db
First, import the node-little-db
library:
const db = require('node-little-db')
Then, get a database object:
const user = db.use('user')
Now, you can perform operations on the user
object.
user.name = 'jack'
user.age = 18
user.hobbies = ['eating', 'sleeping', 'playing Peas']
user.hobbies.push('fish')
user.gender = true
user.address = {
country: 'China',
city: 'Beijing',
}
user.address.city = 'Shanghai'
After running the above code, the content of your file is:
{
"name": "jack",
"age": 18,
"hobbies": [
"eating",
"sleeping",
"playing Peas",
"fish"
],
"address": {
"country": "China",
"city": "Shanghai"
},
"gender": true
}
user.name // 'jack'
user.age // 18
user.hobbies // ['eating', 'sleeping', 'playing Peas']
user.gender // true
user.address // {country: 'China', city: 'Beijing'}
user.address.city // 'Shanghai'
Creates a database object using the specified file. Calling this method will return a proxy object, and any operations performed on this object will be synchronized to the file.
filename
(optional): The file name. If not provided, the default file name db-${Date.now()}.json
will be used.options
(optional): Options object.
options.path
: The file storage path.options.initialData
: Initial data used when creating the file for the first time.options.encoding
: File encoding, defaults to utf-8
.此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。