Aucune description

index.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 eos = function(stream, opts, callback) {
  7. if (typeof opts === 'function') return eos(stream, null, opts);
  8. if (!opts) opts = {};
  9. callback = once(callback || noop);
  10. var ws = stream._writableState;
  11. var rs = stream._readableState;
  12. var readable = opts.readable || (opts.readable !== false && stream.readable);
  13. var writable = opts.writable || (opts.writable !== false && stream.writable);
  14. var onlegacyfinish = function() {
  15. if (!stream.writable) onfinish();
  16. };
  17. var onfinish = function() {
  18. writable = false;
  19. if (!readable) callback();
  20. };
  21. var onend = function() {
  22. readable = false;
  23. if (!writable) callback();
  24. };
  25. var onclose = function() {
  26. if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
  27. if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
  28. };
  29. var onrequest = function() {
  30. stream.req.on('finish', onfinish);
  31. };
  32. if (isRequest(stream)) {
  33. stream.on('complete', onfinish);
  34. stream.on('abort', onclose);
  35. if (stream.req) onrequest();
  36. else stream.on('request', onrequest);
  37. } else if (writable && !ws) { // legacy streams
  38. stream.on('end', onlegacyfinish);
  39. stream.on('close', onlegacyfinish);
  40. }
  41. stream.on('end', onend);
  42. stream.on('finish', onfinish);
  43. if (opts.error !== false) stream.on('error', callback);
  44. stream.on('close', onclose);
  45. return stream;
  46. };
  47. module.exports = eos;