Skip to content

Commit

Permalink
Replace fs.readFile with stream.respondWithFile
Browse files Browse the repository at this point in the history
  • Loading branch information
asbjornu committed Mar 24, 2019
1 parent 6284daf commit 3f9b2b0
Showing 1 changed file with 29 additions and 8 deletions.
37 changes: 29 additions & 8 deletions api.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,34 @@ const options = {
const server = http2.createSecureServer(options);

server.on('stream', (stream, headers, flags) => {
var result = route(headers, stream);
const statCheck = function(stat, statHeaders) {
statHeaders['last-modified'] = stat.mtime.toUTCString();
}

const onError = function(err) {
if (err.code === 'ENOENT') {
var result404 = route('404');
stream.respondWithFile('./resources/404.json', {
'content-type': 'application/problem+json'
});
} else {
stream.respond({
':status': 500
});
}
stream.end();
}

const path = headers[':path'];
const result = route(path);
const file = './resources/' + result.file;

// TODO: Figure out why fs.readFile() works while stream.respondWithFile() doesn't.
var file = './resources/' + result.file;
fs.readFile(file, (err, data) => {
stream.respondWithFile(file, {
':status': result.status,
'content-type': result.contentType,
}, { statCheck, onError });

/*s.readFile(file, (err, data) => {
if (err) {
console.log(err);
return;
Expand All @@ -27,14 +50,12 @@ server.on('stream', (stream, headers, flags) => {
});
stream.write(data);
stream.end();
});
});*/
});

server.listen(3000);

const route = function(headers, stream) {
var path = headers[':path'];

const route = function(path) {
console.log('path', path);

switch (path) {
Expand Down

0 comments on commit 3f9b2b0

Please sign in to comment.