diff --git a/src/websrv.js b/src/websrv.js index 2649134..b0b0eed 100644 --- a/src/websrv.js +++ b/src/websrv.js @@ -178,32 +178,31 @@ function Websrv(tlib) { || contentType === "video/quicktime" || contentType === "audio/mpeg" || contentType === "audio/ogg") && req.headers['range']) { - var start = 0; - var end = 0; - var range = req.headers['range']; - fs.stat(filePath, (err, stat) => { - if(!err) { - if(range != null) { - start = parseInt(range.slice(range.indexOf('bytes=')+6, range.indexOf('-'))); - end = parseInt(range.slice(range.indexOf('-')+1, range.length)); - } - if(isNaN(end) || end == 0) end = stat.size-1; - if(start > end) return; - res.writeHead(206, { - 'Connection':'close', - 'Content-Type':contentType, - 'Content-Length':end - start, - 'Content-Range':'bytes '+start+'-'+end+'/'+stat.size, - 'Transfer-Encoding':'chunked' - }); - var stream = fs.createReadStream(filePath, { flags: 'r', start: start, end: end}); - stream.pipe(res); - } - else { - res.writeHead(404); - res.end('404 - f0ck you', 'utf-8'); - } - }); + fs.readFile(filePath, "binary", function(err, file) { + if(typeof req.headers.range !== 'undefined') { + var range = req.headers.range; + var parts = range.replace(/bytes=/, "").split("-"); + var partialstart = parts[0]; + var partialend = parts[1]; + var total = file.length; + var start = parseInt(partialstart, 10); + var end = partialend ? parseInt(partialend, 10) : total-1; + + res.writeHead(206, { + "Content-Range": "bytes " + start + "-" + end + "/" + (total), + "Accept-Ranges": "bytes", + "Content-Length": (end-start)+1, + "Transfer-Encoding": "chunked", + "Connection": "close" + }); + res.write(file.slice(start, end)+'0', "binary"); + } + else { + res.writeHead(200); + res.write(file, "binary"); + } + res.end(); + }); } else { fs.readFile(filePath, (error, content) => {