typicode / lowdb

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

[Question] Is JSONFile supposed to create the file if it doesn't exist? #514

Closed shennan closed 2 years ago

shennan commented 2 years ago

The title pretty much says it all. When I was using V1, I remember LowDB creating a file if it didn't exist. But perhaps I got that wrong?

Anyway, my current V3 code does not seem to create the file passed to JSONFile adapter:

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

const db = new Low(new JSONFile(path.join(__dirname, 'db.json')))

await db.read()

console.log(db.data) // <= Always "null" unless I first create 'db.json'

Should V3 write the file? Am I wrong in thinking V1 wrote the file?

shennan commented 2 years ago

Apologies, I've just seen that you actually need to write the data yourself if there is no file.

So...

if (db.data === null) {

  db.data = {}

  await db.write()

}

This then creates the file, with the empty object.

This is a departure from V1 where I believe the adapter took care of that part? Closing the issue.