A minimal Express app that reads a JSON file from disk and returns it from an API route.
This demo introduces:
fs.readFile(...)(callback-style)path.join(...)for safe file pathsres.json(...)to return JSON to the client
- Node.js
- npm
Check:
node -v
npm -vnpm installnpm startHome page:
http://localhost:3000/
API route:
http://localhost:3000/api/inventory
You should receive JSON loaded from:
data/inventory.json
npm run watchEdit data/inventory.json, refresh the /api/inventory route, and you’ll see the updated response.
Stop with:
Ctrl + C
- Build a file path:
const filePath = path.join(__dirname, "data", "inventory.json");- Read it:
fs.readFile(filePath, "utf8", (err, data) => { ... });- Parse + return:
const inventory = JSON.parse(data);
res.json(inventory);.
├── app.js
├── package.json
└── data/
└── inventory.jsonNode2Know-LEARN-1.0