从nodeJS中的get请求流式传输axios响应



我正在搜索将readableStream发送(返回(到节点程序中具有axios的方法(myMethod(->我想将响应流式传输到ReadableStream,我可以用它发送给myMethod((调用程序:

// This code does'nt work but that's what I'm trying to do
function myMethod() {
var readableStream = createReadableStream(); // does not exists but that's here to show the concept
const axiosObj = axios({ 
method: 'get',
url: 'https://www.google.fr',
responseType: 'stream' 
}).then(function(res) {
res.data.pipe(readableStream);
}).catch(function(err) {
console.log(err);
});
return readableStream;
}
function myMethodCaller() {
myMethod().on('data', function(chunk) {
// Do some stuffs with the chunks
});
}

我知道我们只能在res.data中做一个到writableStream的管道。我一直在返回可供myMethod((调用程序使用的readableStream。你对此有什么想法吗?

谨致问候,脸红了。

我发现了一个实现

var axios = require('axios');
const Transform = require('stream').Transform;
function streamFromAxios() {
// Create Stream, Writable AND Readable
const inoutStream = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk);
callback();
},
});
// Return promise
const axiosObj = axios({
method: 'get',
url: 'https://www.google.fr',
responseType: 'stream'
}).then(function(res) {
res.data.pipe(inoutStream);
}).catch(function(err) {
console.log(err);
});
return inoutStream;
}
function caller() {
streamFromAxios().on('data', chunk => {
console.log(chunk);
});
}
caller();

最新更新