diff --git a/index.js b/index.js index 99d8e4e..1efa5d1 100644 --- a/index.js +++ b/index.js @@ -19,7 +19,7 @@ send.mime.default_type = 'application/octet-stream' async function fastifyStatic (fastify, opts) { opts.root = normalizeRoot(opts.root) - checkRootPathForErrors(fastify, opts.root) + checkRootPathForErrors(fastify, opts.root, opts.serve); const setHeaders = opts.setHeaders if (setHeaders !== undefined && typeof setHeaders !== 'function') { @@ -408,7 +408,11 @@ function normalizeRoot (root) { return root } -function checkRootPathForErrors (fastify, rootPath) { +function checkRootPathForErrors(fastify, rootPath, serve = true) { + if (serve === false) { + return; + } + if (rootPath === undefined) { throw new Error('"root" option is required') } diff --git a/test/static.test.js b/test/static.test.js index 608d57a..7db0906 100644 --- a/test/static.test.js +++ b/test/static.test.js @@ -4023,3 +4023,51 @@ t.test('content-length in head route should not return zero when using wildcard' }) }) }) + +t.test('serve: false disables root path check', (t) => { + t.plan(3) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + serve: false + }; + const fastify = Fastify(); + fastify.register(fastifyStatic, pluginOptions); + + t.teardown(fastify.close.bind(fastify)); + + fastify.listen({ port: 0 }, (err) => { + t.error(err); + + fastify.server.unref(); + + t.test('/static/index.html', (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT); + simple.concat({ + method: 'GET', + url: 'http://localhost:' + fastify.server.address().port + '/static/index.html' + }, (err, response, body) => { + t.error(err); + t.equal(response.statusCode, 404); + genericErrorResponseChecks(t, response); + t.end() + }); + }); + + t.test('/static/deep/path/for/test/purpose/foo.html', (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT); + simple.concat({ + method: 'GET', + url: 'http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html' + }, (err, response, body) => { + t.error(err); + t.equal(response.statusCode, 404); + genericErrorResponseChecks(t, response); + t.end() + }); + }); + + t.end() + }); +}); \ No newline at end of file