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

青春壹個敷衍的年華 提交于 2019-12-01 12:44:51

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.

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