0

In my dev-environment I prefer to read data from a file instead from the actual API because of performance reason.

I tried to do this like this:

var path = process.env.NODE_ENV === 'production' ? '/pathToExternalApi...' : process.env.pwd + '/assets/mockdata.json';

http.get(path, function (resFromApi, err) {

  var body = '';

  resFromApi.on('data', function (chunk) {
    //console.log(chunk);
    body += chunk;
  });

  resFromApi.on('end', function () {
    //console.log(resFromApi.statusCode + ' path:' + path);
    if (resFromApi.statusCode === 200) {
      cb(JSON.parse(body));
    } else {
      cb(null, 'Statuscode: ' + resFromApi.statusCode);
    }
  });
})

I get 404 when I try to run against file. I've checked that the path is correct.

Cant I use http.get() when to fetch data from file? How do I do this instead?

1

3 Answers 3

1

No, you can not directly use http.get(file_path). You could have a static web server for serving files via http, but that seems to be a nonsense.

I would proceed like that:

if(process.env.NODE_ENV === 'production'){

    http.get("/pathToExternalApi", function (resFromApi, err) {

        var body = '';

        resFromApi.on('data', function (chunk) {
          //console.log(chunk);
          body += chunk;
        });

        resFromApi.on('end', function () {
          //console.log(resFromApi.statusCode + ' path:' + path);
          if(resFromApi.statusCode === 200){
            cb(JSON.parse(body));
          }else{
            cb(null, 'Statuscode: ' + resFromApi.statusCode);
          }
        });
    })

}else{
    fs.readFile(process.env.pwd + '/assets/mockdata.json',function(err,data){
        if(err)
            cb(null, 'Statuscode: ' + err.msg);
        else
            cb(JSON.parse(data));

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

Comments

1

You can't use http module to read a local file. Use fs module instead, for example:

var fs = require("fs");
var file = fs.readFileSync("/assets/mockdata.json");
var mockdata = JSON.parse(file);

If your file is a JSON file, then you can use require() to read that file and parse as JSON:

var mockdata = require("/assets/mockdata.json");

Comments

0

The file needs to be accessible on the server (as URL). The path should be a web relative path or a full http path. Also, try to add the .json mime-type or rename the file the yourfile.js instead of .json.

And yes, if it's nodejs you can use the file system like the previous comment.

Comments

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.