Skip to content

Commit 7bbfeac

Browse files
committed
perf: front-load HTML template and stylesheet at middleware construction
1 parent 6fbafc5 commit 7bbfeac

File tree

2 files changed

+23
-24
lines changed

2 files changed

+23
-24
lines changed

HISTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ unreleased
22
==========
33

44
* Pretty print JSON error response
5+
* perf: front-load HTML template and stylesheet at middleware construction
56
* perf: resolve file paths at start up
67

78
1.4.3 / 2016-01-17

index.js

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,10 @@ exports = module.exports = function errorHandler(options) {
8383
log = logerror
8484
}
8585

86+
// load html and style
87+
var html = fs.readFileSync(TEMPLATE_PATH, 'utf8')
88+
var style = fs.readFileSync(STYLESHEET_PATH, 'utf8')
89+
8690
return function errorHandler(err, req, res, next){
8791
// respect err.statusCode
8892
if (err.statusCode) {
@@ -119,30 +123,24 @@ exports = module.exports = function errorHandler(options) {
119123

120124
// html
121125
if (type === 'html') {
122-
fs.readFile(STYLESHEET_PATH, 'utf8', function (e, style) {
123-
if (e) return next(e);
124-
fs.readFile(TEMPLATE_PATH, 'utf8', function (e, html) {
125-
if (e) return next(e);
126-
var isInspect = !err.stack && String(err) === toString.call(err)
127-
var errorHtml = !isInspect
128-
? escapeHtmlBlock(str.split('\n', 1)[0] || 'Error')
129-
: 'Error'
130-
var stack = !isInspect
131-
? String(str).split('\n').slice(1)
132-
: [str]
133-
var stackHtml = stack
134-
.map(function (v) { return '<li>' + escapeHtmlBlock(v) + '</li>' })
135-
.join('')
136-
var body = html
137-
.replace('{style}', style)
138-
.replace('{stack}', stackHtml)
139-
.replace('{title}', escapeHtml(exports.title))
140-
.replace('{statusCode}', res.statusCode)
141-
.replace(/\{error\}/g, errorHtml)
142-
res.setHeader('Content-Type', 'text/html; charset=utf-8')
143-
res.end(body)
144-
});
145-
});
126+
var isInspect = !err.stack && String(err) === toString.call(err)
127+
var errorHtml = !isInspect
128+
? escapeHtmlBlock(str.split('\n', 1)[0] || 'Error')
129+
: 'Error'
130+
var stack = !isInspect
131+
? String(str).split('\n').slice(1)
132+
: [str]
133+
var stackHtml = stack
134+
.map(function (v) { return '<li>' + escapeHtmlBlock(v) + '</li>' })
135+
.join('')
136+
var body = html
137+
.replace('{style}', style)
138+
.replace('{stack}', stackHtml)
139+
.replace('{title}', escapeHtml(exports.title))
140+
.replace('{statusCode}', res.statusCode)
141+
.replace(/\{error\}/g, errorHtml)
142+
res.setHeader('Content-Type', 'text/html; charset=utf-8')
143+
res.end(body)
146144
// json
147145
} else if (type === 'json') {
148146
var error = { message: err.message, stack: err.stack };

0 commit comments

Comments
 (0)