1

I just set up my first node HTTP server, and I am trying to get the response data from a JSON file in my application. When I declare a JSON object in the server.js file, all works well.

 data = "{"sample json" : "this is a test"}";

But I want to replace data with a static JSON file at data/sample.json

Here's an example in my server.js file

const http = require("http");
const hostname = "localhost";
const port = 3000;

const server = http.createServer(function(req, res) {

    data = // this is where I want to get the JSON data from data/sample.json
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.write(data);
    res.end();

});
1

2 Answers 2

3

Solved with fs.readFile()

const http = require("http");
const hostname = "localhost";
const port = 3000;
const fs = require('fs');

const server = http.createServer(function(req, res) {
    filePath = './data/sample.json';
    
    if (req.path == '/data/sample.json') {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                if (error.code == 'ENOENT') {
                    response.writeHead(404);
                    response.end(error.code);
                }
                else {
                    response.writeHead(500);
                    response.end(error.code);
                }
            }
            else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(content);
            }
        });
    }
    else {
      response.writeHead(404);
      response.end('restricted path');
    }

});
Sign up to request clarification or add additional context in comments.

5 Comments

What's missing here is looking for errors from fs.readFile() (when the error argument is non-null) where you should probably send a 404 or 500 response. Note also that you're sending the same file for all possible requests to your server when you presumably should only be sending this file for one particular req.path.
@jfriend00 Thanks, I updated my answer. The only problem I'm having now is the req.path check. The request still seems to be responding with the sample.json object regardless of the path.
@jfriend00 - resolved , I just needed to restart the server.
And, then add an else to your path check and send a 404 so your server always sends some sort of response, regardless of path. If you don't send a response, then the request just hangs out for awhile, eventually timing out which is not a healthy thing to do.
FYI, another way to do this is fs.createReadStream(filePath).pipe(res).
0

In case someone else tumbles upon this question. The answer above has ton of typos and errors and incomplete. Here is a working solution.

const http = require("http");
const hostname = "localhost";
const fs = require('fs');
const port = 8080;

const server = http.createServer(function(req, res) {
    filePath = './data/sample.json';
    if (req.url == '/api/data') {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                if (error.code == 'ENOENT') {
                    res.writeHead(404);
                    res.end(error.code);
                }
                else {
                    res.writeHead(500);
                    res.end(error.code);
                }
            }
            else {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(content);
            }
        });
    }
    else {
        res.writeHead(404);
        res.end('404 NOT FOUND');
    }
});

server.listen(port, hostname, () => {
    console.log('Server started on port ', port);
});

1 Comment

Please let us know where you made changes and why you made them instead of just posting your code.

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.