Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 19 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ const supportedEncodings = ['br', 'gzip', 'deflate']
send.mime.default_type = 'application/octet-stream'

/** @type {import("fastify").FastifyPluginAsync<import("./types").FastifyStaticOptions>} */
async function fastifyStatic (fastify, opts) {
opts.root = normalizeRoot(opts.root)
checkRootPathForErrors(fastify, opts.root)
async function fastifyStatic(fastify, opts) {
if (opts.serve !== false) {
opts.root = normalizeRoot(opts.root)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Dipali127
Why should normalizeRoot also be skipped?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this scenario we are not using root if I'm not wrong

checkRootPathForErrors(fastify, opts.root)
}

const setHeaders = opts.setHeaders
if (setHeaders !== undefined && typeof setHeaders !== 'function') {
Expand Down Expand Up @@ -66,7 +68,7 @@ async function fastifyStatic (fastify, opts) {
hide: opts.schemaHide !== undefined ? opts.schemaHide : true
},
logLevel: opts.logLevel,
errorHandler (error, request, reply) {
errorHandler(error, request, reply) {
if (error?.code === 'ERR_STREAM_PREMATURE_CLOSE') {
reply.request.raw.destroy()
return
Expand Down Expand Up @@ -117,7 +119,7 @@ async function fastifyStatic (fastify, opts) {
...routeOpts,
method: ['HEAD', 'GET'],
path: prefix + '*',
handler (req, reply) {
handler(req, reply) {
pumpSendToReply(req, reply, '/' + req.params['*'], sendOptions.root)
}
})
Expand Down Expand Up @@ -181,7 +183,7 @@ async function fastifyStatic (fastify, opts) {
* @param {import("@fastify/send").SendOptions} [pumpOptions]
* @param {Set<string>} [checkedEncodings]
*/
async function pumpSendToReply (
async function pumpSendToReply(
request,
reply,
pathname,
Expand Down Expand Up @@ -299,7 +301,7 @@ async function fastifyStatic (fastify, opts) {
}

if (metadata.error.code === 'ENOENT') {
// when preCompress is enabled and the path is a directory without a trailing slash
// when preCompress is enabled and the path is a directory without a trailing slash
if (opts.preCompressed && encoding) {
if (opts.redirect !== true) {
const indexPathname = findIndexFile(pathname, options.root, options.index)
Expand Down Expand Up @@ -384,7 +386,7 @@ async function fastifyStatic (fastify, opts) {
}
}

function setUpHeadAndGet (routeOpts, route, file, rootPath) {
function setUpHeadAndGet(routeOpts, route, file, rootPath) {
const toSetUp = Object.assign({}, routeOpts, {
method: ['HEAD', 'GET'],
url: route,
Expand All @@ -397,7 +399,7 @@ async function fastifyStatic (fastify, opts) {
}

/** @type {import("fastify").RouteHandlerMethod} */
async function serveFileHandler (req, reply) {
async function serveFileHandler(req, reply) {
const routeConfig = req.routeOptions?.config
return pumpSendToReply(req, reply, routeConfig.file, routeConfig.rootPath)
}
Expand All @@ -407,7 +409,7 @@ async function fastifyStatic (fastify, opts) {
* @param {import("./types").FastifyStaticOptions['root']} root
* @returns {import("./types").FastifyStaticOptions['root']}
*/
function normalizeRoot (root) {
function normalizeRoot(root) {
if (root === undefined) {
return root
}
Expand Down Expand Up @@ -435,7 +437,7 @@ function normalizeRoot (root) {
* @param {import("./types").FastifyStaticOptions['root']} rootPath
* @returns {void}
*/
function checkRootPathForErrors (fastify, rootPath) {
function checkRootPathForErrors(fastify, rootPath) {
if (rootPath === undefined) {
throw new Error('"root" option is required')
}
Expand Down Expand Up @@ -468,7 +470,7 @@ function checkRootPathForErrors (fastify, rootPath) {
* @param {import("./types").FastifyStaticOptions['root']} rootPath
* @returns {void}
*/
function checkPath (fastify, rootPath) {
function checkPath(fastify, rootPath) {
if (typeof rootPath !== 'string') {
throw new TypeError('"root" option must be a string')
}
Expand Down Expand Up @@ -498,7 +500,7 @@ function checkPath (fastify, rootPath) {
* @param {string} path
* @return {string}
*/
function getContentType (path) {
function getContentType(path) {
const type = send.mime.getType(path) || send.mime.default_type

if (!send.isUtf8MimeType(type)) {
Expand All @@ -513,7 +515,7 @@ function getContentType (path) {
* @param {import("./types").FastifyStaticOptions['index']} [indexFiles]
* @return {string|boolean}
*/
function findIndexFile (pathname, root, indexFiles = ['index.html']) {
function findIndexFile(pathname, root, indexFiles = ['index.html']) {
if (Array.isArray(indexFiles)) {
return indexFiles.find(filename => {
const p = path.join(root, pathname, filename)
Expand All @@ -534,7 +536,7 @@ function findIndexFile (pathname, root, indexFiles = ['index.html']) {
* @param {import('fastify').FastifyRequest['headers']} headers
* @param {Set<string>} checked
*/
function getEncodingHeader (headers, checked) {
function getEncodingHeader(headers, checked) {
if (!('accept-encoding' in headers)) return

// consider the no-preference token as gzip for downstream compat
Expand All @@ -550,7 +552,7 @@ function getEncodingHeader (headers, checked) {
* @param {string} encoding
* @returns {string}
*/
function getEncodingExtension (encoding) {
function getEncodingExtension(encoding) {
switch (encoding) {
case 'br':
return 'br'
Expand All @@ -564,7 +566,7 @@ function getEncodingExtension (encoding) {
* @param {string} url
* @return {string}
*/
function getRedirectUrl (url) {
function getRedirectUrl(url) {
let i = 0
// we detect how many slash before a valid path
for (; i < url.length; ++i) {
Expand Down
11 changes: 11 additions & 0 deletions test/root/example.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test file</title>
</head>
<body>
<h1>hello fastify</h1>
</body>
</html>
40 changes: 40 additions & 0 deletions test/serve-option.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'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 })
console.log('Server running at http://localhost:0')
fastify.server.unref()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fastify.server.unref()
t.after(() => fastify.close())


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()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fastify.server.unref()
t.after(() => fastify.close())


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"');
})