* Serves static files, with API similar to expressjs * * @public * @function serveStaticFiles * @param {String} directory - the directory to serve files from * @param {Object} opts - an options object, which is optional * @param {Number} [opts.maxAge=0] - specify max age in millisecs
(directory, opts)
| 60 | * ); |
| 61 | */ |
| 62 | function serveStaticFiles(directory, opts) { |
| 63 | // make a copy of the options that will be passed to send |
| 64 | var optionsPlugin = shallowCopy(opts || {}); |
| 65 | var optionsSend = shallowCopy(opts || {}); |
| 66 | // lets assert some options |
| 67 | assert.object(optionsSend, 'options'); |
| 68 | assert.object(optionsPlugin, 'options'); |
| 69 | assert.string(directory, 'directory'); |
| 70 | |
| 71 | // `send` library relies on `root` to specify the root folder |
| 72 | // to look for files |
| 73 | optionsSend.root = path.resolve(directory); |
| 74 | // `setHeaders` is only understood by our plugin |
| 75 | if (optionsSend.setHeaders) { |
| 76 | delete optionsSend.setHeaders; |
| 77 | } |
| 78 | |
| 79 | return function handleServeStaticFiles(req, res, next) { |
| 80 | // Check to make sure that this was either a GET or a HEAD request |
| 81 | if (req.method !== 'GET' && req.method !== 'HEAD') { |
| 82 | return next(new MethodNotAllowedError('%s', req.method)); |
| 83 | } |
| 84 | // we expect the params to have `*`: |
| 85 | // This allows the router to accept any file path |
| 86 | var requestedFile = req.params['*'] || 'index.html'; |
| 87 | // This is used only for sending back correct error message text |
| 88 | var requestedFullPath = req.url; |
| 89 | // Rely on `send` library to create a stream |
| 90 | var stream = send(req, requestedFile, optionsSend); |
| 91 | |
| 92 | // Lets handle the various events being emitted by send module |
| 93 | |
| 94 | // stream has ended, must call `next()` |
| 95 | stream.on('end', function handleEnd() { |
| 96 | return next(); |
| 97 | }); |
| 98 | |
| 99 | // when `send` encounters any `error`, we have the opportunity |
| 100 | // to handle the errors here |
| 101 | stream.on('error', function handleError(err) { |
| 102 | var respondWithError = null; |
| 103 | // When file does not exist |
| 104 | if (err.statusCode === 404) { |
| 105 | respondWithError = new ResourceNotFoundError(requestedFullPath); |
| 106 | } else { |
| 107 | // or action is forbidden (like requesting a directory) |
| 108 | respondWithError = new NotAuthorizedError(requestedFullPath); |
| 109 | } |
| 110 | return next(respondWithError); |
| 111 | }); |
| 112 | |
| 113 | // If the request was for directory and that directory did not |
| 114 | // have index.html, this will be called |
| 115 | stream.on('directory', function handleDirectoryRequest() { |
| 116 | next(new NotAuthorizedError('%s', requestedFullPath)); |
| 117 | return; |
| 118 | }); |
| 119 |
nothing calls this directly
no test coverage detected