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

Blu*_*ulb 4 stream node.js axios

我正在寻找在节点程序中使用 axios 向方法 (myMethod) 发送(返回)可读流 -> 我想将响应流式传输到可用于发送给 myMethod() 调用者的 ReadableStream:

// 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;
}
Run Code Online (Sandbox Code Playgroud)
function myMethodCaller() {
   myMethod().on('data', function(chunk) {
      // Do some stuffs with the chunks
   });
}
Run Code Online (Sandbox Code Playgroud)

我知道我们只能在 res.data 中做一个到 writableStream 的管道。我陷入了返回 myMethod() 调用者可用的 ReadStream 的困境。你对此有什么想法吗?

问候,模糊。

Blu*_*ulb 5

我找到了一个实现

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();
Run Code Online (Sandbox Code Playgroud)