slavhadz
slavhadz

Reputation: 57

How to read file content in Node.js and convert the data to JSON?

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.

Upvotes: 2

Views: 1211

Answers (2)

RadekF
RadekF

Reputation: 486

Save the buffer into a variable and then use toString() method and after that JSON.parse

Upvotes: 2

Jorge Cabot
Jorge Cabot

Reputation: 191

What you want to do is specify the encoding like so:

fs.readFile(path.join(__dirname, 'data', 'filename.json'), 'utf8', (err, content) => {
        res.setHeader('Content-Type', 'application/json');
        res.send(content); // content will be a string
    })

Otherwise according to the documentation you will get the Buffer.

Upvotes: 0

Related Questions