I am working on creating the classical car API. Now I'm trying to pull a JSON Array from an external file.
I made a step toward a resolution, however my "solution" will return the full object, instead of the array json.
This is from the vehicles.js file, found under api/routes/
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const router = express.Router();
router.get('/', (req, res, next) => {
res.status(200).sendFile(path.join(__dirname, '../resources', 'vehicles.json'));
});
export default router;
The app.js looks like this:
import express from 'express';
const app = express();
import vehiclesRoute from './api/routes/vehicles.js';
app.use('/vehicles', vehiclesRoute);
export default app;
Something else I tried was in the lines of:
import parsedJSON from './resources/vehicles.json';
var vehiclesJSON = parsedJSON.vehicles;
router.get('/', (req, res, next) => {
let vehiclesJSONpath = path.join(__dirname, '../resources', 'vehicles.json');
res.status(200).fetch(vehiclesJSONpath)
.then(res => res.json())
.then(data => console.log(data));
});
Will close this. The solution was simple.
'use strict';
let rawdata = fs.readFileSync('api/resources/vehicles.json');
let vehicles = JSON.parse(rawdata);
Then, in order to be able to get it as a response:
router.get('/', (req, res, next) => {
res.status(200).json(vehicles);
});
Saved by: https://stackabuse.com/reading-and-writing-json-files-with-node-js/