简体   繁体   English

如何使用Node.js从json文件中读取数据并将读取的数据显示为html?

[英]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. 它能够在控制台上显示我在.json中的数据。 However when I am trying to create a server and post the data using res.end, it doesn't really work. 但是,当我尝试使用res.end创建服务器并发布数据时,它并没有真正起作用。

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? 我应该如何处理从.json获取的数据以便用于我的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: http模块不支持将Objects作为响应(它支持缓冲区或字符串),因此您必须这样做:

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

however if used express you could do this 但如果使用express你可以这样做

res.send(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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