Skip to content
Permalink
Browse files

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.
  • Loading branch information...
vojtajina committed Aug 5, 2014
1 parent dd1971f commit eb5bd53ff0b6dc01e247fce9af01d0ed97d8c9ba
Showing with 11 additions and 2 deletions.
  1. +8 −0 lib/middleware/common.js
  2. +3 −2 test/unit/middleware/karma.spec.coffee
@@ -26,13 +26,19 @@ var serve404 = function(response, path) {


var createServeFile = function(fs, directory) {
var cache = Object.create(null);

return function(filepath, response, transform, content) {
var responseData;

if (directory) {
filepath = directory + filepath;
}

if (!content && cache[filepath]) {
content = cache[filepath];
}

// serve from cache
if (content) {
response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'));
@@ -51,6 +57,8 @@ var createServeFile = function(fs, directory) {
return serve404(response, filepath);
}

cache[filepath] = data.toString();

response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'));

// call custom transform fn to transform the data
@@ -21,16 +21,17 @@ describe 'middleware.karma', ->
'debug.html': mocks.fs.file(0, 'DEBUG\n%SCRIPTS%\n%X_UA_COMPATIBLE%')
'karma.js': mocks.fs.file(0, 'root: %KARMA_URL_ROOT%, v: %KARMA_VERSION%')

serveFile = require('../../../lib/middleware/common').createServeFile fsMock, '/karma/static'
createServeFile = require('../../../lib/middleware/common').createServeFile
createKarmaMiddleware = require('../../../lib/middleware/karma').create

handler = filesDeferred = nextSpy = response = null
handler = serveFile = filesDeferred = nextSpy = response = null

beforeEach ->
clientConfig = foo: 'bar'
nextSpy = sinon.spy()
response = new HttpResponseMock
filesDeferred = q.defer()
serveFile = createServeFile fsMock, '/karma/static'
handler = createKarmaMiddleware filesDeferred.promise, serveFile,
'/base/path', '/__karma__/', clientConfig

0 comments on commit eb5bd53

Please sign in to comment.
You can’t perform that action at this time.