In your example, the HTTP request is getting executed when NodeJS reads your file (which you probably don't want it to do because it's a bad habbit).
You can solve this by using a callback.
const req = require("request");
module.exports = function (successCb, errorCb) {
req("http://example.com/car/items.json", (err, res, body) => {
if (err) return errorCb(err);
// You may want to add an additional check for statusCode 200
// How you handle that depends on your scenario.
successCb(JSON.parse(body));
})
}
From another file
const yourReqModule = require('your-req-module')
yourReqModule(function(jsonResponse) {
handleJsonResponse...
}, function (error) {
// Handle error
});
By using this technique, the HTTP request wont be executed until you actually run yourReqModule.api()
.
Edit:
You should always include error handling. I've updated the code with an example implementation of that.