-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream-range-request.js
52 lines (46 loc) · 1.91 KB
/
stream-range-request.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'use strict';
const marklogic = require('marklogic');
const connection = require('./connection');
const db = marklogic.createDatabaseClient(connection);
const qb = marklogic.queryBuilder;
const http = require('http');
http.createServer((req, res) => {
const uri = req.url;
if (uri === '/favicon.ico') {
res.end();
return;
}
if (uri !== '/') {
db.documents.probe(uri).result().then(response => {
let {contentLength, contentType} = response;
contentLength = Number(contentLength);
let rangeRequest = req.headers.range;
if (rangeRequest) {
let [partialStart, partialEnd] = rangeRequest.replace(/bytes=/, '').split('-');
let start = Number(partialStart);
let end = partialEnd ? Number(partialEnd) : contentLength;
let chunksize = end - start;
let streamEnd = end;
end = end - 1;
let header = {
'Content-Disposition': 'filename=' + uri,
'Content-Range': 'bytes ' + start + '-' + end + '/' + contentLength,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType
};
res.writeHead(206, header);
let stream = db.documents.read({uris: uri, range: [start, streamEnd]}).stream('chunked');
stream.pipe(res);
stream.on('error', error => console.log(error));
stream.on('end', () => res.end());
} else {
res.setHeader('Content-Type', contentType);
res.setHeader('Content-Length', contentLength);
let stream = db.documents.read({uris: uri}).stream('chunked');
stream.on('error', error => console.log(error));
stream.pipe(res);
}
}).catch((error) => console.log(error));
}
}).listen(3000, () => console.log('Magic happens on port 3000. Please open a browser and go to an endpoint that represents a URI in your MarkLogic database, e.g.: "http://localhost:3000/clips/bunny.mp4"'));