I am trying to send data from a .json file as a response with Node.js. I am pretty new to it, and i don't know how to handle the Buffer.
This is what I did:
const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', (req, res, next) => {
fs.readFile(path.join(__dirname, 'data', 'filename.json'), (err, content) => {
res.send(JSON.stringify(content));
})
});
app.listen(port, () => {
console.log(`server is running on port: ${port}`)
});
I expect to get the data in JSON format but what I get is a Buffer or just numbers. I guess i'm not getting some concepts right.
Save the buffer into a variable and then use toString()
method and after that JSON.parse