问题
I'm trying to get some data from a third party service using the node request module and return this data as string from a function. My perception was that request()
returns a readable stream since you can do request(...).pipe(writeableStream)
which - I thought - implies that I can do
function getData(){
var string;
request('someurl')
.on('data', function(data){
string += data;
})
.on('end', function(){
return string;
});
}
but this does not really work. I think I have some wrong perception of how request() or node streams really work. Can somebody clear up my confusion here?
回答1:
It does work exactly the way you explained. Maybe the problem that you're facing is due to the asynchronous nature of node.js. I'm quite sure you're calling your getData()
in a synchronous way. Try this and see if you're request
call is not returning something:
request('someurl')
.on('data', function(data){
console.log(data.toString());
.on('end', function(){
console.log("This is the end...");
});
Take a look at this piece of article here. It's not short, but it explains how to write your code in order to deal with this kind of situation.
回答2:
What I get is you want to access string
later and you thought the request
would return a completed string. If so, you can't do it synchronously, you have to put your code to process the completed string
in the end
event handler like this:
function getData(){
var string;
request('someurl')
.on('data', function(data){
string += data;
})
.on('end', function(){
processString(string);
});
}
getData();
来源:https://stackoverflow.com/questions/24477699/why-doesnt-request-on-work-in-node-js