Skip to content

Commit

Permalink
Refactor responding to common function
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed May 25, 2017
1 parent 506626c commit 2b7755a
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions index.js
Expand Up @@ -208,11 +208,7 @@ serveIndex.html = function _html(req, res, files, next, dir, showUp, icons, path
// render html
render(locals, function (err, body) {
if (err) return next(err);

var buf = new Buffer(body, 'utf8');
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Content-Length', buf.length);
res.end(buf);
send(res, 'text/html', body)
});
});
});
Expand All @@ -223,25 +219,15 @@ serveIndex.html = function _html(req, res, files, next, dir, showUp, icons, path
*/

serveIndex.json = function _json(req, res, files) {
var body = JSON.stringify(files);
var buf = new Buffer(body, 'utf8');

res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Content-Length', buf.length);
res.end(buf);
send(res, 'application/json', JSON.stringify(files))
};

/**
* Respond with text/plain.
*/

serveIndex.plain = function _plain(req, res, files) {
var body = files.join('\n') + '\n';
var buf = new Buffer(body, 'utf8');

res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Content-Length', buf.length);
res.end(buf);
send(res, 'text/plain', (files.join('\n') + '\n'))
};

/**
Expand Down Expand Up @@ -503,6 +489,17 @@ function removeHidden(files) {
});
}

/**
* Send a response.
* @private
*/

function send (res, type, body) {
res.setHeader('Content-Type', type + '; charset=utf-8')
res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
res.end(body, 'utf8')
}

/**
* Stat all files and return array of stat
* in same order.
Expand Down

0 comments on commit 2b7755a

Please sign in to comment.