javascript 为什么 request.on() 在 Node.js 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24477699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't request.on() work in Node.js
提问by Flavio
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
我正在尝试使用节点请求模块从第三方服务获取一些数据,并将此数据作为字符串从函数返回。我的看法是request()返回一个可读的流,因为你可以这样做request(...).pipe(writeableStream)- 我认为 - 意味着我可以做到
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?
但这并没有真正起作用。我想我对 request() 或节点流的真正工作方式有一些错误的看法。有人可以在这里澄清我的困惑吗?
回答by Rodrigo Medeiros
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 requestcall is not returning something:
它确实按照您解释的方式工作。也许您面临的问题是由于 node.js 的异步特性。我很确定您getData()是以同步方式调用您的。试试这个,看看你的request电话是否没有返回任何东西:
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.
在此处查看这篇文章。它并不短,但它解释了如何编写代码以处理这种情况。
回答by user3102569
What I get is you want to access stringlater and you thought the requestwould return a completed string. If so, you can't do it synchronously, you have to put your code to process the completed stringin the endevent handler like this:
我得到的是您想string稍后访问,并且您认为request将返回一个完整的字符串。如果是这样,你不能同步做,你必须把你的代码string在end事件处理程序中处理完成,如下所示:
function getData(){
var string;
request('someurl')
.on('data', function(data){
string += data;
})
.on('end', function(){
processString(string);
});
}
getData();

