jsonfile vs write-json-file vs lowdb
JSONファイル操作
jsonfilewrite-json-filelowdb類似パッケージ:
JSONファイル操作

JSONファイル操作ライブラリは、Node.jsアプリケーションでJSON形式のデータを読み書きするためのツールです。これらのライブラリは、ファイルシステムと連携してデータを保存したり、既存のデータを読み込んだりする機能を提供します。特に、設定ファイルや小規模なデータストレージに便利です。jsonfileはシンプルで使いやすいAPIを提供し、JSONファイルの読み書きを簡単に行えます。lowdbは軽量なデータベースとして機能し、JSONファイルをバックエンドに持ちながら、簡単なCRUD操作をサポートします。write-json-fileは、JSONデータをファイルに書き込む際に、既存のファイルを安全に上書きすることができるライブラリです。

npmのダウンロードトレンド
3 年
GitHub Starsランキング
統計詳細
パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
jsonfile82,825,6011,20910.8 kB24ヶ月前MIT
write-json-file3,029,4672237.38 kB03ヶ月前MIT
lowdb915,52122,39422.9 kB162年前MIT
機能比較: jsonfile vs write-json-file vs lowdb

ファイルの読み書き

  • jsonfile:

    jsonfileは、JSONファイルの読み書きをシンプルに行うことができます。特に、ファイルの内容を簡単に取得したり、更新したりすることができます。

  • write-json-file:

    write-json-fileは、JSONデータをファイルに書き込むことに特化しており、既存のファイルを安全に上書きすることができます。

  • lowdb:

    lowdbは、JSONファイルをデータベースのように扱い、読み書きだけでなく、データの追加、更新、削除が簡単に行えます。

データの整合性

  • jsonfile:

    jsonfileは、データの整合性を特に保証する機能はありませんが、シンプルな読み書き操作には適しています。

  • write-json-file:

    write-json-fileは、ファイルに書き込む前にデータを検証する機能はありませんが、上書き時に一時ファイルを使用することで、データの整合性を保つことができます。

  • lowdb:

    lowdbは、データをJSON形式で保存するため、整合性はファイルシステムに依存しますが、データベースのように扱うことで、整合性を保ちながら操作できます。

CRUD操作

  • jsonfile:

    jsonfileは、基本的な読み書き操作に特化しており、CRUD操作のうち、Create(作成)と Read(読み取り)に焦点を当てています。

  • write-json-file:

    write-json-fileは、データの作成や更新に特化していますが、削除操作はサポートしていません。

  • lowdb:

    lowdbは、完全なCRUD操作をサポートしており、データの作成、読み取り、更新、削除が簡単に行えます。

ファイルの上書き

  • jsonfile:

    jsonfileは、ファイルを上書きする際に特別な処理は行いません。単純に新しいデータでファイルを更新します。

  • write-json-file:

    write-json-fileは、ファイルを上書きする際に、一時ファイルを使用して安全に上書きするため、データの損失を防ぐことができます。

  • lowdb:

    lowdbは、データを更新する際に、既存のデータを上書きすることができますが、上書きの際の整合性はユーザーが管理する必要があります。

コード例

  • jsonfile:

    jsonfileを使用したファイルの読み書き例

    const jsonfile = require('jsonfile');
    const file = 'data.json';
    
    // データの書き込み
    const obj = { name: 'Alice', age: 25 };
    jsonfile.writeFile(file, obj, { spaces: 2 }, err => {
      if (err) console.error(err);
    });
    
    // データの読み込み
    jsonfile.readFile(file, (err, data) => {
      if (err) console.error(err);
      console.log(data);
    });
    
  • write-json-file:

    write-json-fileを使用した安全なファイル書き込み例

    const writeJsonFile = require('write-json-file');
    const file = 'data.json';
    const data = { name: 'Bob', age: 30 };
    
    // データの書き込み
    writeJsonFile(file, data, { spaces: 2 }).then(() => {
      console.log('データが書き込まれました。');
    });
    
  • lowdb:

    lowdbを使用したCRUD操作の例

    const { Low, JSONFile } = require('lowdb');
    const file = 'db.json';
    const adapter = new JSONFile(file);
    const db = new Low(adapter);
    
    // データベースの初期化
    await db.read();
    db.data ||= { users: [] };
    
    // データの追加
    db.data.users.push({ name: 'Alice', age: 25 });
    await db.write();
    
    // データの読み取り
    console.log(db.data.users);
    
    // データの更新
    db.data.users[0].age = 26;
    await db.write();
    
    // データの削除
    db.data.users.splice(0, 1);
    await db.write();
    
選び方: jsonfile vs write-json-file vs lowdb
  • jsonfile:

    jsonfileを選択するのは、シンプルで直感的なAPIを求めている場合です。特に、JSONファイルの読み書きを迅速に行いたいプロジェクトに適しています。

  • write-json-file:

    write-json-fileを選択するのは、JSONデータをファイルに安全に書き込みたい場合です。特に、既存のファイルを上書きする際に、データの整合性を保ちたいプロジェクトに適しています。

  • lowdb:

    lowdbを選択するのは、軽量なデータベース機能が必要な場合です。JSONファイルをバックエンドに持ちながら、簡単なCRUD操作を行いたいアプリケーションに最適です。

jsonfile のREADME

Node.js - jsonfile

Easily read/write JSON files in Node.js. Note: this module cannot be used in the browser.

npm Package linux build status windows Build status

Standard JavaScript

Why?

Writing JSON.stringify() and then fs.writeFile() and JSON.parse() with fs.readFile() enclosed in try/catch blocks became annoying.

Installation

npm install --save jsonfile

API


readFile(filename, [options], callback)

options (object, default undefined): Pass in any fs.readFile options or set reviver for a JSON reviver.

  • throws (boolean, default: true). If JSON.parse throws an error, pass this error to the callback. If false, returns null for the object.
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file, function (err, obj) {
  if (err) console.error(err)
  console.dir(obj)
})

You can also use this method with promises. The readFile method will return a promise if you do not pass a callback function.

const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file)
  .then(obj => console.dir(obj))
  .catch(error => console.error(error))

readFileSync(filename, [options])

options (object, default undefined): Pass in any fs.readFileSync options or set reviver for a JSON reviver.

  • throws (boolean, default: true). If an error is encountered reading or parsing the file, throw the error. If false, returns null for the object.
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'

console.dir(jsonfile.readFileSync(file))

writeFile(filename, obj, [options], callback)

options: Pass in any fs.writeFile options or set replacer for a JSON replacer. Can also pass in spaces, or override EOL string or set finalEOL flag as false to not save the file with EOL at the end.

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFile(file, obj, function (err) {
  if (err) console.error(err)
})

Or use with promises as follows:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFile(file, obj)
  .then(res => {
    console.log('Write complete')
  })
  .catch(error => console.error(error))

formatting with spaces:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) {
  if (err) console.error(err)
})

overriding EOL:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) {
  if (err) console.error(err)
})

disabling the EOL at the end of file:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) {
  if (err) console.log(err)
})

appending to an existing JSON file:

You can use fs.writeFile option { flag: 'a' } to achieve this.

const jsonfile = require('jsonfile')

const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }

jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) {
  if (err) console.error(err)
})

writeFileSync(filename, obj, [options])

options: Pass in any fs.writeFileSync options or set replacer for a JSON replacer. Can also pass in spaces, or override EOL string or set finalEOL flag as false to not save the file with EOL at the end.

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFileSync(file, obj)

formatting with spaces:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFileSync(file, obj, { spaces: 2 })

overriding EOL:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' })

disabling the EOL at the end of file:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = { name: 'JP' }

jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false })

appending to an existing JSON file:

You can use fs.writeFileSync option { flag: 'a' } to achieve this.

const jsonfile = require('jsonfile')

const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }

jsonfile.writeFileSync(file, obj, { flag: 'a' })

License

(MIT License)

Copyright 2012-2016, JP Richardson jprichardson@gmail.com