index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. var once = require('once');
  2. var noop = function() {};
  3. var isRequest = function(stream) {
  4. return stream.setHeader && typeof stream.abort === 'function';
  5. };
  6. var isChildProcess = function(stream) {
  7. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  8. };
  9. var eos = function(stream, opts, callback) {
  10. if (typeof opts === 'function') return eos(stream, null, opts);
  11. if (!opts) opts = {};
  12. callback = once(callback || noop);
  13. var ws = stream._writableState;
  14. var rs = stream._readableState;
  15. var readable = opts.readable || (opts.readable !== false && stream.readable);
  16. var writable = opts.writable || (opts.writable !== false && stream.writable);
  17. var onlegacyfinish = function() {
  18. if (!stream.writable) onfinish();
  19. };
  20. var onfinish = function() {
  21. writable = false;
  22. if (!readable) callback.call(stream);
  23. };
  24. var onend = function() {
  25. readable = false;
  26. if (!writable) callback.call(stream);
  27. };
  28. var onexit = function(exitCode) {
  29. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  30. };
  31. var onerror = function(err) {
  32. callback.call(stream, err);
  33. };
  34. var onclose = function() {
  35. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  36. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  37. };
  38. var onrequest = function() {
  39. stream.req.on('finish', onfinish);
  40. };
  41. if (isRequest(stream)) {
  42. stream.on('complete', onfinish);
  43. stream.on('abort', onclose);
  44. if (stream.req) onrequest();
  45. else stream.on('request', onrequest);
  46. } else if (writable && !ws) { // legacy streams
  47. stream.on('end', onlegacyfinish);
  48. stream.on('close', onlegacyfinish);
  49. }
  50. if (isChildProcess(stream)) stream.on('exit', onexit);
  51. stream.on('end', onend);
  52. stream.on('finish', onfinish);
  53. if (opts.error !== false) stream.on('error', onerror);
  54. stream.on('close', onclose);
  55. return function() {
  56. stream.removeListener('complete', onfinish);
  57. stream.removeListener('abort', onclose);
  58. stream.removeListener('request', onrequest);
  59. if (stream.req) stream.req.removeListener('finish', onfinish);
  60. stream.removeListener('end', onlegacyfinish);
  61. stream.removeListener('close', onlegacyfinish);
  62. stream.removeListener('finish', onfinish);
  63. stream.removeListener('exit', onexit);
  64. stream.removeListener('end', onend);
  65. stream.removeListener('error', onerror);
  66. stream.removeListener('close', onclose);
  67. };
  68. };
  69. module.exports = eos;