Why doesn't request.on() work in Node.js

老子叫甜甜 提交于 2019-12-01 10:45:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!