1

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?

1
  • It's already JSON on disk. No need to parse. res.end needs a buffer or a string, not an object. Commented Jul 9, 2014 at 23:25

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

This is great! But I was looking for the stringify function. Thank you still
this is the correct way to do it if you wanted to simply output a file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.