user3669481
user3669481

Reputation: 327

How to use Node.js to read data from a json file and display the read data into html?

I am a complete newbie and just did something like this:

    var fs = require('fs');
    var file = __dirname + '/data.json';
    var http = require ('http');
    var server = http.createServer(function (req, res){
    res.writeHead(200);

    fs.readFile(file, 'utf8', function (err, data) {
            if (err) {
            console.log('Error: ' + err);
            return;
            }

    data = JSON.parse(data);

    res.end(data);
    });


    });
        server.listen(8000);

When I am doing:

    data = JSON.parse(data);
    console.dir(data);

Instead of

    data = JSON.parse(data);
    res.end(data);

It is able to display the data I have in .json on the console. However when I am trying to create a server and post the data using res.end, it doesn't really work.

Could someone offer some insights? Is it because the "data" I have here is only an object? How should I process the data I get from .json in order to use for my html?

Upvotes: 1

Views: 5587

Answers (2)

Chad
Chad

Reputation: 9859

The http module doesn't support Objects as a response (it supports buffers or a strings) so you have to do this:

res.end(JSON.stringify(data));

however if used express you could do this

res.send(data);

Upvotes: 2

generalhenry
generalhenry

Reputation: 17319

Since the file is already in the right format, you can simply pipe it to the response.

var fs = require('fs');
var file = __dirname + '/data.json';
var http = require ('http');
var server = http.createServer(function (req, res){
  res.writeHead(200, {'Content-Type': 'application/json'});
  fs.createReadStream(file, 'utf8').pipe(res);
});
server.listen(8000);

Upvotes: 2

Related Questions