LowDB静的JSONファイルデータベースの紹介

6492 ワード

LowDB
NPM version
Build Status
Need a quick way to get a local database?
神速なローカルストレージ方式が必要ですか?
LowDBはnodeベースの純JSONファイルデータベースであり、readMeファイルの中国語翻訳である.
Example(例)
var low = require('lowdb')
var db = low('db.json')

db('posts').push({ title: 'lowdb is awesome'})

データベースはdb.jsonに自動的に保存されます
Database is automatically saved to db.json
{
  "posts": [
    { "title": "lowdb is awesome" }
  ]
}

任意のlodashメソッドを使用してデータベースをクエリーおよび操作できます.
You can query and manipulate it using any lodash method
db('posts').find({ title: 'lowdb is awesome' })

Install(インストール)
npm install lowdb --save

Features
  • Small(軽量級)
  • Server less(サーバ不要)
  • lodash rich API(lodash豊富なAPI)
  • In-memory or disk-based(メモリとハードディスクベースのストレージ)
  • Hackable (mixins, id, encryption, ...)

  • lowDBは8つの方法と属性しかないので、勉強しやすいです.
    It's also very easy to learn and use since it has only 8 methods and properties.
    json-server、jsonplaceholder、other projectsはlowDBによって強力に駆動されます
    lowdb powers json-server package, jsonplaceholder website and other projects.
    API
    low([filename, options])
    ハードディスク(HDD)またはメモリベースのデータベースインスタンスを作成します.ファイル名パラメータが存在する場合、このファイルはロードまたは作成されます.
    Creates a disk-based or in-memory database instance. If a filename is provided, it loads or creates it.
    var db = low()          // in-memory
    var db = low('db.json') // disk-based
    
    filenameパラメータが指定されている場合は、オプションを設定できます.
    When a filename is provided you can set options.
    var db = low('db.json', {
      autosave: true, // automatically save database on change (default: true)
      async: true     // asynchronous write (default: true)
    })
    

    low.stringify(obj) and low.parse(str)
    これらのオプションを書き換えるのはJSONの文字列化と解析を定義することから来ます
    Overwrite these methods to customize JSON stringifying and parsing.
    __ db._ __
    データベースlodashインスタンスでは、必要なユーティリティまたはサードパーティライブラリを追加できます.
    Database lodash instance. Use it for example to add your own utility functions or third-party libraries.
    db._.mixin({
      second: function(array) {
        return array[1]
      }
    })
    
    var song1 = db('songs').first()
    var song2 = db('songs').second()
    

    db.object
    下位データベース・オブジェクトの操作
    Use whenever you want to access or modify the underlying database object.
    if (db.object.songs) console.log('songs array exists')
    

    db.save([filename])
    指定したファイルへのデータベースの保存
    Saves database to file.
    var db = low('db.json')
    db.save() // saves to db.json
    db.save('copy.json')
    

    注意:データベース・オブジェクトを直接操作した場合は、saveを手動で呼び出して保存する必要があります.
    Note: In case you directly modify the content of the database object, you'll need to manually call save
    delete db.object.songs
    db.save()
    

    db.saveSync([filename]) db.save()の同期実行バージョンSynchronous version of db.save()ガイド
    操作
    LowDBですべてのlodash APIを使用できるため、操作データをクエリーする方法がたくさんあります.以下はいくつかの入門レベルの例です.
    With LowDB you get access to the entire lodash API, so there's many ways to query and manipulate data. Here are a few examples to get you started.
    必ずデータが参考から戻ってくることを覚えておいてください.これは、返されるオブジェクトに対する操作がデータベースの変更をもたらす可能性があることを意味し、.cloneDeep()を使用してこのような状況を回避することができる.
    Please note that data is returned by reference, this means that modifications to returned objects may change the database. To avoid such behaviour, you need to use .cloneDeep() .
    もちろん、チェーンメソッドの実行は不活性であり、value()呼び出し後に文が実行される.
    Also, the execution of chained methods is lazy, that is, execution is deferred until .value() is called.
    上位5曲をソート
    Sort the top five songs.
    db('songs')
      .chain()
      .where({published: true})
      .sortBy('views')
      .take(5)
      .value()
    

    タイトル検索
    Retrieve song titles.
    db('songs').pluck('titles')
    

    曲の数を取得
    Get the number of songs.
    db('songs').size()
    
    songsデータベースの深度クローン作成
    Make a deep clone of songs.
    db('songs').cloneDeep()
    

    歌のデータを更新
    Update a song.
    db('songs')
      .chain()
      .find({ title: 'low!' })
      .assign({ title: 'hi!'})
      .value()
    

    曲を削除
    Remove songs.
    db('songs').remove({ title: 'low!' })
    

    Id support(サポートID)
    IDによるデータの取得は、特にサーバにおいて非常に有用である.LowDBにIDベースのリソース管理サポートを追加するには、2つのオプションがあります.
    Being able to retrieve data using an id can be quite useful, particularly in servers. To add id-based resources support to lowdb, you have 2 options.
    underscore-dbは、IDベースのリソースの作成と操作に一連の補助を提供します.
    underscore-db provides a set of helpers for creating and manipulating id-based resources.
    var db = low('db.json')
    
    db._.mixin(require('underscore-db'))
    
    var songId = db('songs').insert({ title: 'low!' }).id
    var song   = db('songs').getById(songId)
    

    uuidはユニークなidを返す
    uuid returns a unique id.
    var uuid = require('uuid')
    
    var songId = db('songs').push({ id: uuid(), title: 'low!' }).id
    var song   = db('songs').find({ id: songId })
    

    Encryption support(暗号化サポート)
    場合によっては、データベースの内容を解読しにくいようにしたい場合があります.low.stringifylow.parseを書き換えることで、カスタム暗号化方法を追加できます.
    In some cases, you may want to make it harder to read database content. By overwriting, low.stringify and low.parse , you can add custom encryption.
    var crypto = require('crypto')
    
    var cipher = crypto.createCipher('aes256', secretKey)
    var decipher = crypto.createDecipher('aes256', secretKey)
    
    low.stringify = function(obj) {
      var str = JSON.stringify(obj)
      return cipher.update(str, 'utf8', 'hex') + cipher.final('hex')
    }
    
    low.parse = function(encrypted) {
      var str = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8')
      return JSON.parse(str)
    }