How to Store the Response of a GET Request In a Lo

2019-04-10 04:26发布

问题:

I know the way to make a GET request to a URL using the request module. Eventually, the code just prints the GET response within the command shell from where it has been spawned.

How do I store these GET response in a local variable so that I can use it else where in the program?

This is the code i use:

var request = require("request");
request("http://www.stackoverflow.com", function(error, response, body) {
    console.log(body);
}); 

回答1:

The easiest way (but it has pitfalls--see below) is to move body into the scope of the module.

var request = require("request");
var body;


request("http://www.stackoverflow.com", function(error, response, data) {
    body = data;
});

However, this may encourage errors. For example, you might be inclined to put console.log(body) right after the call to 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!

This will not work because request() is asynchronous, so it returns control before body is set in the callback.

You might be better served by creating body as an event emitter 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 using promises.



标签: node.js get