问题描述
我正在尝试使用节点请求模块从第三方服务中获取一些数据,并从函数中以字符串形式返回此数据.我的理解是request()
返回可读流,因为您可以执行request(...).pipe(writeableStream)
-我认为-暗示我可以执行
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;
});
}
但这确实不起作用.我认为我对request()或节点流的实际工作方式有一些误解.有人可以在这里消除我的困惑吗?
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?
推荐答案
它确实按照您解释的方式工作.也许您面临的问题是由于node.js的异步特性造成的.我很确定您正在以同步方式调用getData()
.尝试此操作,看看您是否在request
呼叫中未返回任何内容:
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.
这篇关于为什么request.on()在Node.js中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!