javascript - Read a file using HTTP in Node.JS -


in dev-environment prefer read data file instead actual api because of performance reason.

i tried 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 404 when try run against file. i've checked path correct.

cant use http.get() when fetch data file? how do instead?

no, can not directly use http.get(file_path). have static web server serving files via http, seems nonsense.

i proceed 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));      }) } 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -