檔案讀取與寫入
- jsonfile:
jsonfile
提供簡單的讀取和寫入 JSON 檔案的功能。它支援異步和同步操作,適合各種使用場景。 - write-json-file:
write-json-file
專注於寫入 JSON 檔案,提供高效能的寫入方法,並支援流式寫入和格式化。 - lowdb:
lowdb
允許讀取和寫入 JSON 檔案,但它的主要功能是作為一個小型資料庫,支援 CRUD 操作。
資料庫功能
- jsonfile:
jsonfile
不具備資料庫功能,僅提供檔案操作。 - write-json-file:
write-json-file
不具備資料庫功能,專注於檔案寫入。 - lowdb:
lowdb
提供完整的資料庫功能,支援 CRUD 操作,並允許使用者透過鍵值對方式存取資料。
效能
- jsonfile:
jsonfile
在處理小型檔案時效能良好,但對於大型檔案,讀取和寫入速度會受到影響。 - write-json-file:
write-json-file
在寫入大型檔案時表現優異,特別是使用流式寫入時,可以有效降低記憶體使用量。 - lowdb:
lowdb
由於需要處理資料庫操作,效能會受到資料量大小的影響,但對於小型資料集來說仍然相當快。
格式化選項
- jsonfile:
jsonfile
在寫入檔案時不提供格式化選項。 - write-json-file:
write-json-file
提供格式化選項,允許使用者在寫入檔案時指定縮排級別,這對於提高檔案可讀性非常有幫助。 - lowdb:
lowdb
允許使用者自訂資料格式,但預設情況下不提供格式化功能。
範例程式碼
- jsonfile:
使用
jsonfile
讀取和寫入 JSON 檔案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
寫入 JSON 檔案const writeJsonFile = require('write-json-file'); const file = 'data.json'; const data = { name: 'Bob', age: 30 }; // 寫入檔案 writeJsonFile(file, data, { indent: 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({ id: 1, name: 'Alice' }); await db.write(); // 讀取使用者 console.log(db.data.users);