diff --git a/index.js b/index.js index a4e81f6..383b4cc 100644 --- a/index.js +++ b/index.js @@ -19,8 +19,10 @@ send.mime.default_type = 'application/octet-stream' /** @type {import("fastify").FastifyPluginAsync} */ async function fastifyStatic (fastify, opts) { - opts.root = normalizeRoot(opts.root) - checkRootPathForErrors(fastify, opts.root) + if (opts.serve !== false) { + opts.root = normalizeRoot(opts.root) + checkRootPathForErrors(fastify, opts.root) + } const setHeaders = opts.setHeaders if (setHeaders !== undefined && typeof setHeaders !== 'function') { diff --git a/test/root/example.html b/test/root/example.html new file mode 100644 index 0000000..013d3d6 --- /dev/null +++ b/test/root/example.html @@ -0,0 +1,11 @@ + + + + + + test file + + +

hello fastify

+ + \ No newline at end of file diff --git a/test/serve-option.test.js b/test/serve-option.test.js new file mode 100644 index 0000000..f1b1ec1 --- /dev/null +++ b/test/serve-option.test.js @@ -0,0 +1,39 @@ +'use strict' + +const path = require('node:path') +const assert = require('node:assert') +const { test } = require('node:test') +const Fastify = require('fastify') +const fastifyStatic = require('../index.js') + +test('should not serve static files when serve is false', async t => { + const fastify = Fastify() + fastify.register(fastifyStatic, { + serve: false + }) + + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const res = await fetch('http://localhost:' + fastify.server.address().port + '/public/example.html') + assert.strictEqual(res.status, 404) +}) + +test('should serve static files when serve is true', async t => { + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, 'root'), + prefix: '/public/' + }) + + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const res = await fetch('http://localhost:' + fastify.server.address().port + '/public/example.html') + assert.strictEqual(res.status, 200) + + const content = await res.text() + assert.ok(content.includes('hello'), 'File content should contain "hello"') +}) diff --git a/types/index.d.ts b/types/index.d.ts index d410bb2..2edc55e 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -85,7 +85,7 @@ declare namespace fastifyStatic { } export interface FastifyStaticOptions extends SendOptions { - root: string | string[] | URL | URL[]; + root?: string | string[] | URL | URL[]; prefix?: string; prefixAvoidTrailingSlash?: boolean; serve?: boolean;