How to close a https stream in node.js?

by cortez.connelly , in category: PHP General , 2 months ago

How to close a https stream in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 2 months ago

@cortez.connelly 

To close a HTTPS stream in Node.js, you can simply call the end() or destroy() method on the stream object. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const https = require('https');

const req = https.get('https://example.com', (res) => {
  // Handle response
  res.on('data', (data) => {
    console.log(data.toString());
  });
  
  // Close the stream
  res.on('end', () => {
    console.log('Stream closed');
  });
  
  // Close the stream
  req.end();
});

req.on('error', (err) => {
  console.error(err);
});

// Or you can use destroy method
// req.destroy();


In this example, we make a HTTPS request using https.get() method and handle the response data. Once we are done with the stream, we call end() method on the response object res to close the stream. Alternatively, you can use the destroy() method to forcefully close the stream.


Remember to handle any errors that may occur during the streaming process.