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?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Joe
  • 4,274
  • 32
  • 95
  • 175

3 Answers3

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");
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
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));

    })
}
Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52
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.