Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implements #8 content-range using code from streamer.js #93

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 31 additions & 18 deletions lib/ecstatic.js
Expand Up @@ -141,24 +141,6 @@ var ecstatic = module.exports = function (dir, options) {
});

function serve(stat) {

// TODO: Helper for this, with default headers.
res.setHeader('etag', etag(stat));
res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
res.setHeader('cache-control', cache);

// Return a 304 if necessary
if ( req.headers
&& (
(req.headers['if-none-match'] === etag(stat))
|| (new Date(Date.parse(req.headers['if-modified-since'])) >= stat.mtime)
)
) {
return status[304](res, next);
}

res.setHeader('content-length', stat.size);

// Do a MIME lookup, fall back to octet-stream and handle gzip
// special case.
var contentType = mime.lookup(file), charSet;
Expand All @@ -177,6 +159,37 @@ var ecstatic = module.exports = function (dir, options) {
contentType = mime.lookup(path.basename(file, ".gz"));
}

var range = (req.headers && req.headers['range']);
if (range) {
var total = stat.size;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
var fstream = fs.createReadStream(file, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': contentType || 'application/octet-stream' });
fstream.pipe(res);
return;
}

// TODO: Helper for this, with default headers.
res.setHeader('etag', etag(stat));
res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
res.setHeader('cache-control', cache);

// Return a 304 if necessary
if ( req.headers
&& (
(req.headers['if-none-match'] === etag(stat))
|| (new Date(Date.parse(req.headers['if-modified-since'])) >= stat.mtime)
)
) {
return status[304](res, next);
}

res.setHeader('content-length', stat.size);
res.setHeader('content-type', contentType || 'application/octet-stream');

if (req.method === "HEAD") {
Expand Down