How to store the response of a GET request in a local variable in Node JS
I know a way to make a GET url request using a module request
. In the end, the code just prints the GET response to the shell where it was generated from.
How do I store this GET response in a local variable so I can use it elsewhere in the program?
This is the code I am using:
var request = require("request");
request("http://www.stackoverflow.com", function(error, response, body) {
console.log(body);
});
source to share
The easiest way (but it has pitfalls - see below) is to move body
to the area of ββthe module.
var request = require("request");
var body;
request("http://www.stackoverflow.com", function(error, response, data) {
body = data;
});
However, this can cause errors. For example, you can bow console.log(body)
right after the call request()
.
var request = require("request");
var body;
request("http://www.stackoverflow.com", function(error, response, data) {
body = data;
});
console.log(body); // THIS WILL NOT WORK!
It won't work because it request()
is asynchronous, so it returns before the callback is set body
.
You might be better off creating body
as event source and subscribing to events.
var request = require("request");
var EventEmitter = require("events").EventEmitter;
var body = new EventEmitter();
request("http://www.stackoverflow.com", function(error, response, data) {
body.data = data;
body.emit('update');
});
body.on('update', function () {
console.log(body.data); // HOORAY! THIS WORKS!
});
Another option is to switch to promises .
source to share