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.

http-stream.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var mime = require("mime");
  2. /*
  3. * Must be set to a function which takes an options argument with
  4. * 'start' and 'end', and returns a readStream.
  5. * The readStream must have the additional properties
  6. * 'filesize' and 'filename' set.
  7. */
  8. exports.readStreamCreator = null;
  9. exports.httpPath = "/http-stream";
  10. exports.init = function(app) {
  11. app.get("/http-stream", (req, res) => {
  12. if (exports.readStreamCreator == null) {
  13. res.writeHead(500);
  14. throw "readStreamCreator not set!";
  15. }
  16. var rs;
  17. var parts = [];
  18. if (req.headers.range) {
  19. parts = req.headers.range.replace("bytes=", "").split("-");
  20. var start = parseInt(parts[0]);
  21. var end = parseInt(parts[1]);
  22. var options = {};
  23. if (!isNaN(start)) options.start = start;
  24. if (!isNaN(end)) options.end = end;
  25. rs = exports.readStreamCreator(options);
  26. } else {
  27. rs = exports.readStreamCreator();
  28. }
  29. var start = parseInt(parts[0]) || 0;
  30. var end = parts[1] ? parseInt(parts[1]) : rs.filesize - 1;
  31. var chunksize = end - start + 1;
  32. if (chunksize > rs.filesize || start > end || end >= rs.filesize) {
  33. res.writeHead(416);
  34. res.end("Range not satisfiable. Start: "+start+", end: "+end);
  35. return;
  36. }
  37. res.writeHead(req.headers.range ? 206 : 200, {
  38. "icy-name": rs.filename,
  39. "content-length": chunksize,
  40. "content-type": mime.lookup(rs.filename),
  41. "content-range": "bytes "+start+"-"+end+"/"+rs.filesize,
  42. "accept-ranges": "bytes"
  43. });
  44. if (req.method === "HEAD")
  45. return res.end();
  46. rs.pipe(res);
  47. });
  48. }
  49. exports.stop = function() {
  50. exports.readStreamCreator = null;
  51. }