Skip to content

Commit 2b7755a

Browse files
committed
Refactor responding to common function
1 parent 506626c commit 2b7755a

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

index.js

+14-17
Original file line numberDiff line numberDiff line change
@@ -208,11 +208,7 @@ serveIndex.html = function _html(req, res, files, next, dir, showUp, icons, path
208208
// render html
209209
render(locals, function (err, body) {
210210
if (err) return next(err);
211-
212-
var buf = new Buffer(body, 'utf8');
213-
res.setHeader('Content-Type', 'text/html; charset=utf-8');
214-
res.setHeader('Content-Length', buf.length);
215-
res.end(buf);
211+
send(res, 'text/html', body)
216212
});
217213
});
218214
});
@@ -223,25 +219,15 @@ serveIndex.html = function _html(req, res, files, next, dir, showUp, icons, path
223219
*/
224220

225221
serveIndex.json = function _json(req, res, files) {
226-
var body = JSON.stringify(files);
227-
var buf = new Buffer(body, 'utf8');
228-
229-
res.setHeader('Content-Type', 'application/json; charset=utf-8');
230-
res.setHeader('Content-Length', buf.length);
231-
res.end(buf);
222+
send(res, 'application/json', JSON.stringify(files))
232223
};
233224

234225
/**
235226
* Respond with text/plain.
236227
*/
237228

238229
serveIndex.plain = function _plain(req, res, files) {
239-
var body = files.join('\n') + '\n';
240-
var buf = new Buffer(body, 'utf8');
241-
242-
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
243-
res.setHeader('Content-Length', buf.length);
244-
res.end(buf);
230+
send(res, 'text/plain', (files.join('\n') + '\n'))
245231
};
246232

247233
/**
@@ -503,6 +489,17 @@ function removeHidden(files) {
503489
});
504490
}
505491

492+
/**
493+
* Send a response.
494+
* @private
495+
*/
496+
497+
function send (res, type, body) {
498+
res.setHeader('Content-Type', type + '; charset=utf-8')
499+
res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
500+
res.end(body, 'utf8')
501+
}
502+
506503
/**
507504
* Stat all files and return array of stat
508505
* in same order.

0 commit comments

Comments
 (0)