'How can I close the axios response stream based on some condition at server side?

I want to close the Axios response stream based on some conditions. I am not able to do this by passing the callback

const response = await axios({
                method: 'get',
                signal,
                url: this.url,
                httpsAgent: this.agent,
                timeout: this.wait_for_connect_ms,
                auth: { username: this.username, password: this.password },
                responseType: 'stream',
            });
      
  response.data.on('data', async (chunks) => {
    
    if(exit) {
      // close the stream exit and return
    }
    });


Solution 1:[1]

try unisg Cancel Token

const axios = require('axios');

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

const response = await axios({
    method: 'get',
    signal,
    url: this.url,
    httpsAgent: this.agent,
    timeout: this.wait_for_connect_ms,
    auth: { username: this.username, password: this.password },
    responseType: 'stream',
    cancelToken: source.token
});

then call cancel with your own logic

source.cancel('Kill Request!');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naor Tedgi