ralfting

NodeJs Stream

Nov 22nd, 2013
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var http = require('http'), fileSystem = require('fs'), path = require('path'), util = require('util');
  2.  
  3. http.createServer(function(request, response){
  4.     var filePath = path.join(__dirname, "stream", "video.mp4");
  5.     var stat = fileSystem.statSync(filePath);
  6.     // inicio do pedaço
  7.     var inicio = 0;
  8.     // Fim do pedaço
  9.     var fim = 0;
  10.      
  11.     var range = request.headers.range;
  12.     console.log(range);
  13.  
  14.     if (range) {
  15.         console.log('Existe range');
  16.         inicio  = parseInt(range.slice(range.indexOf("byte=")+6,range.indexOf("-")));
  17.         fim     = parseInt(range.slice(range.indexOf("-")+1, range.length));
  18.     }
  19.  
  20.     if (inicio > fim)
  21.         return;
  22.    
  23.     if (isNaN(fim) || fim == 0) {
  24.         fim = stat.size - 1;
  25.     }
  26.     response.write(206, {
  27.         'Content-Type'  : 'video/mp4',
  28.         'Content-Range' : 'bytes ' + inicio + '-' + fim + '/' + stat.size,
  29.         'Content-Length': stat.size,
  30.         'Transfer-Encoding':'chunked'
  31.     });
  32.     console.log(inicio);
  33.     console.log(fim);
  34.  
  35.     var readStream = fileSystem.createReadStream(filePath, { flags: 'r', start: inicio, end: fim });
  36.  
  37.     util.pump(readStream, response);
  38. }).listen(3000);
Add Comment
Please, Sign In to add comment