Skip to content

Commit eb5bd53

Browse files
committed
fix(web-server): cache static files
Files in `karma/static/*` were always read from file system. These files typically don’t change (except when developing Karma itself) and so it makes sense to cache them in memory. Especially `./static/context.html`, which is read for every test run. The main reason for this change is that when using native events (non-polling), watching can easily hit the EMFILE limit and then this `fs.readFile()` can be super delayed. This was easily reproducible problem in AngularJS test suite.
1 parent dd1971f commit eb5bd53

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

lib/middleware/common.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,19 @@ var serve404 = function(response, path) {
2626

2727

2828
var createServeFile = function(fs, directory) {
29+
var cache = Object.create(null);
30+
2931
return function(filepath, response, transform, content) {
3032
var responseData;
3133

3234
if (directory) {
3335
filepath = directory + filepath;
3436
}
3537

38+
if (!content && cache[filepath]) {
39+
content = cache[filepath];
40+
}
41+
3642
// serve from cache
3743
if (content) {
3844
response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'));
@@ -51,6 +57,8 @@ var createServeFile = function(fs, directory) {
5157
return serve404(response, filepath);
5258
}
5359

60+
cache[filepath] = data.toString();
61+
5462
response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'));
5563

5664
// call custom transform fn to transform the data

test/unit/middleware/karma.spec.coffee

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,17 @@ describe 'middleware.karma', ->
2121
'debug.html': mocks.fs.file(0, 'DEBUG\n%SCRIPTS%\n%X_UA_COMPATIBLE%')
2222
'karma.js': mocks.fs.file(0, 'root: %KARMA_URL_ROOT%, v: %KARMA_VERSION%')
2323

24-
serveFile = require('../../../lib/middleware/common').createServeFile fsMock, '/karma/static'
24+
createServeFile = require('../../../lib/middleware/common').createServeFile
2525
createKarmaMiddleware = require('../../../lib/middleware/karma').create
2626

27-
handler = filesDeferred = nextSpy = response = null
27+
handler = serveFile = filesDeferred = nextSpy = response = null
2828

2929
beforeEach ->
3030
clientConfig = foo: 'bar'
3131
nextSpy = sinon.spy()
3232
response = new HttpResponseMock
3333
filesDeferred = q.defer()
34+
serveFile = createServeFile fsMock, '/karma/static'
3435
handler = createKarmaMiddleware filesDeferred.promise, serveFile,
3536
'/base/path', '/__karma__/', clientConfig
3637

0 commit comments

Comments
 (0)