typicode / lowdb

Simple and fast JSON database
MIT License
21.3k stars 918 forks source link

data not persisting when reading file on server restart #548

Closed jmsbrett closed 1 year ago

jmsbrett commented 1 year ago

I have a project set up with nodejs and lowdb.

Nodejs version: v16.16.0 Lowdb: v3.0.0

Issue persisting data after restart:

import { join, dirname } from 'path'
import { Low, JSONFile } from 'lowdb'
import { fileURLToPath } from 'url'

const __dirname = dirname(fileURLToPath(import.meta.url));

// Use JSON file for storage
const file = join(__dirname, './db.json');
const adapter = new JSONFile(file);
const db = new Low(adapter);

db.data ||= {
    scenarios: ["Operational Scenario 1", "Operational Scenario 2"],
    tests: [
        {
            name: "Operational Scenario 1",
            command: "ls -la"
        },
        {
            name: "Operational Scenario 1",
            command: "ls -la"
        },
        {
            name: "Operational Scenario 2",
            command: "ls -la"
        },
        {
            name: "Operational Scenario 2",
            command: "ls -la"
        },
    ]
}

await db.write();

export default db;

It seem that the db.data does not actually exist and then lowdb overwrites the file.

typicode commented 1 year ago

I see nothing wrong with your code. However I can't reproduce the issue. Closing as the issue is old and you may have already found a solution.