Comparing version 0.0.2 to 0.0.4
@@ -56,2 +56,46 @@ var fs = require('fs'), | ||
Server.prototype.parseRange = function(head, stat) { | ||
var parts = head.split('='), | ||
type = parts.shift(), | ||
set = (parts.shift() || '').split(',').shift(), // paf only supports one range as of now | ||
opts = {stream: {}, headers: {}}; | ||
opts.stream.start = 0; | ||
opts.stream.end = stat.size; | ||
if (!type || !set || type !== 'bytes') | ||
return opts; | ||
if (set[0] === '-') { | ||
opts.stream.start = stat.size + parseInt(set); | ||
opts.headers['Content-Range'] = 'bytes ' + opts.stream.start + '/' + stat.size; | ||
opts.headers['Content-Length'] = -parseInt(set); | ||
} else { | ||
set = set.split('-'); | ||
opts.stream.start = set.shift(); | ||
opts.stream.end = set.shift(); | ||
opts.headers['Content-Range'] = 'bytes ' + opts.stream.start + '-' + opts.stream.end + '/' + stat.size; | ||
opts.headers['Content-Length'] = opts.stream.end - opts.stream.start; | ||
} | ||
opts.stream.start = parseInt(opts.stream.start) || 0; | ||
opts.stream.end = parseInt(opts.stream.end) || stat.size; | ||
if ( | ||
opts.stream.end > stat.size || | ||
opts.stream.start > stat.size || | ||
opts.stream.start > opts.stream.end | ||
) { | ||
opts.stream.start = 0; | ||
opts.stream.end = stat.size; | ||
opts.headers['Content-Length'] = stat.size; | ||
} | ||
return opts; | ||
}; | ||
Server.prototype.serve = function(req, res) { | ||
@@ -67,5 +111,10 @@ var self = this; | ||
res.writeHead(200, {'Content-Type': mime[path.extname(p).slice(1)] || 'application/octet-stream'}); | ||
var range = self.parseRange(req.headers.range || '', stat), | ||
headers = range.headers; | ||
fs.createReadStream(p).pipe(res); | ||
headers['Content-Type'] = mime[path.extname(p).slice(1)] || 'application/octet-stream'; | ||
headers['Content-Length'] = headers['Content-Length'] || stat.size; | ||
res.writeHead(200, headers); | ||
fs.createReadStream(p, range.stream).pipe(res); | ||
}); | ||
@@ -72,0 +121,0 @@ }); |
{ | ||
"name": "paf", | ||
"version": "0.0.2", | ||
"version": "0.0.4", | ||
"description": "Shitty, static and cacheless http server", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -19,2 +19,3 @@ var request = require('request'), | ||
request('http://localhost:8001/test', function(req, res, body) { | ||
expect(res.headers['content-length']).to.be('6'); | ||
expect(body).to.be('nexgay'); | ||
@@ -24,2 +25,15 @@ done(); | ||
}); | ||
it('should answer requests correctly if there is a "Range" header', function(done) { | ||
request.get({ | ||
url: 'http://localhost:8001/test', | ||
headers: { | ||
'Range': 'bytes=0-3' | ||
} | ||
}, function(req, res, body) { | ||
expect(res.headers['content-length']).to.be('3'); | ||
expect(body).to.be('nex'); | ||
done(); | ||
}); | ||
}); | ||
@@ -26,0 +40,0 @@ it('should return 404 if file doesn\'t exist', function(done) { |
13946
411