Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alternative stream error handling for older Nodes, without stream.pipeline #372

Merged
merged 8 commits into from
Aug 26, 2021

Conversation

tomas
Copy link
Owner

@tomas tomas commented Aug 26, 2021

Fixes #371 (regression introduced in #370)

Handles cleanup of sockets correctly when response stream is piped to a writable one that errors out.

An important note, is that when a writable stream fails, the readable it's reading from isn't aborted but simply unpiped, unless using stream.pipeline. So if you're using resp.pipe(writableStream) in your code, you need to manually abort the request to make sure the socket is properly disposed of, and prevent any possible memleaks because of it. Eg.:

  var resp = needle.get('some.url.com/path')
  var writableStream = fs.createWriteStream('/some/file');
  resp.pipe(writableStream);

  writableStream.on('close', function(e) {
    if (!resp.done) resp.abort();
  })

Or for a shorter version:

  var resp = needle.get('some.url.com/path')
  resp.pipe(fs.createWriteStream('/some/file'))
      .on('close', function(e) { if (!resp.done) resp.abort() })

Remember the Stream#pipe() function returns the destination/writable stream, not the origin/readable one

This PR includes the resp.done boolean that lets you check whether the request completed or not, and the abort() method which is an alias for resp.request.abort().

In short, if you are using a newer version of Node, please use stream.pipeline.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2.9.0 breaks on Node.js 8
1 participant