You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.0 KiB

4 years ago
  1. /*!
  2. * destroy
  3. * Copyright(c) 2014 Jonathan Ong
  4. * MIT Licensed
  5. */
  6. 'use strict'
  7. /**
  8. * Module dependencies.
  9. * @private
  10. */
  11. var ReadStream = require('fs').ReadStream
  12. var Stream = require('stream')
  13. /**
  14. * Module exports.
  15. * @public
  16. */
  17. module.exports = destroy
  18. /**
  19. * Destroy a stream.
  20. *
  21. * @param {object} stream
  22. * @public
  23. */
  24. function destroy(stream) {
  25. if (stream instanceof ReadStream) {
  26. return destroyReadStream(stream)
  27. }
  28. if (!(stream instanceof Stream)) {
  29. return stream
  30. }
  31. if (typeof stream.destroy === 'function') {
  32. stream.destroy()
  33. }
  34. return stream
  35. }
  36. /**
  37. * Destroy a ReadStream.
  38. *
  39. * @param {object} stream
  40. * @private
  41. */
  42. function destroyReadStream(stream) {
  43. stream.destroy()
  44. if (typeof stream.close === 'function') {
  45. // node.js core bug work-around
  46. stream.on('open', onOpenClose)
  47. }
  48. return stream
  49. }
  50. /**
  51. * On open handler to close stream.
  52. * @private
  53. */
  54. function onOpenClose() {
  55. if (typeof this.fd === 'number') {
  56. // actually close down the fd
  57. this.close()
  58. }
  59. }