简体   繁体   中英

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?

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM