Skip to content

Instantly share code, notes, and snippets.

@nonnullish
Created December 13, 2022 08:26
Show Gist options
  • Save nonnullish/7b8926295a5dbf60d0174cd97f7e207d to your computer and use it in GitHub Desktop.
Save nonnullish/7b8926295a5dbf60d0174cd97f7e207d to your computer and use it in GitHub Desktop.
Run JSON-server with multiple database .json files.
/*
JSON-server is unable to serve multiple files at once.
(https://stackoverflow.com/questions/36836424/cant-watch-multiple-files-with-json-server)
This is a quick script for making a joint db.json file.
Directory structure:
db/
├─ chunks/
│ ├─ example1.json
│ ├─ example2.json
├─ db.json
├─ util.js
The names of the chunk files will constitute as keys in the joint database.
Example chunk .json file structure:
example.json
{
"data": [
{
"key": "field"
}
]
}
To run: node .\db\util.js
To run server: json-server --watch --no-cors db.json
*/
const dbs = './db/chunks';
const fs = require('fs');
const jsons = fs.readdirSync(dbs).filter((filename) => filename.includes('.json'));
fs.writeFileSync('./db/db.json', '');
let db = {};
for (const json of jsons) {
const data = fs.readFileSync(`./db/chunks/${json}`, 'utf8');
db[json.slice(0, -5)] = JSON.parse(data)['data'];
}
fs.appendFileSync('./db/db.json', JSON.stringify(db, null, '\t'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment