Socket
Socket
Sign inDemoInstall

fastify-static

Package Overview
Dependencies
4
Maintainers
11
Versions
55
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 3.3.1 to 3.4.0

example/public2/test.css

7

example/server-compress.js

@@ -7,7 +7,10 @@ 'use strict'

fastify
// compress everything
// Compress everything.
.register(require('fastify-compress'), { threshold: 0 })
.register(require('../'), { root: path.join(__dirname, '/public') })
.register(require('../'), {
// An absolute path containing static files to serve.
root: path.join(__dirname, '/public')
})
.listen(3000, err => {
if (err) throw err
})

@@ -8,21 +8,22 @@ 'use strict'

// Handlebar template for listing files and directories.
const template = `
<html><body>
<html>
<body>
dirs
<ul>
{{#dirs}}
<li><a href="{{href}}">{{name}}</a></li>
{{/dirs}}
</ul>
dirs
list
<ul>
{{#dirs}}
<li><a href="{{href}}">{{name}}</a></li>
{{/dirs}}
</ul>
list
<ul>
{{#files}}
<li><a href="{{href}}" target="_blank">{{name}}</a></li>
{{/files}}
</ul>
</body></html>
<ul>
{{#files}}
<li><a href="{{href}}" target="_blank">{{name}}</a></li>
{{/files}}
</ul>
</body>
</html>
`

@@ -33,7 +34,13 @@ const handlebarTemplate = Handlebars.compile(template)

.register(require('..'), {
// An absolute path containing static files to serve.
root: path.join(__dirname, '/public'),
// Do not append a trailing slash to prefixes.
prefixAvoidTrailingSlash: true,
// Return a directory listing with a handlebar template.
list: {
// html or json response? html requires a render method.
format: 'html',
// A list of filenames that trigger a directory list response.
names: ['index', 'index.html', 'index.htm', '/'],
// You can provide your own render method as needed.
render: (dirs, files) => handlebarTemplate({ dirs, files })

@@ -40,0 +47,0 @@ }

@@ -7,5 +7,8 @@ 'use strict'

fastify
.register(require('../'), { root: path.join(__dirname, '/public') })
.register(require('../'), {
// An absolute path containing static files to serve.
root: path.join(__dirname, '/public')
})
.listen(3000, err => {
if (err) throw err
})

@@ -34,3 +34,3 @@ // Definitions by: Jannik <https://github.com/jannikkeye>

export interface FastifyStaticOptions {
root: string;
root: string | string[];
prefix?: string;

@@ -37,0 +37,0 @@ prefixAvoidTrailingSlash?: boolean;

@@ -10,8 +10,9 @@ 'use strict'

const fp = require('fastify-plugin')
const util = require('util')
const globPromise = util.promisify(glob)
const dirList = require('./lib/dirList')
function fastifyStatic (fastify, opts, next) {
const error = checkRootPathForErrors(fastify, opts.root)
if (error !== undefined) return next(error)
async function fastifyStatic (fastify, opts) {
checkRootPathForErrors(fastify, opts.root)

@@ -21,3 +22,3 @@ const setHeaders = opts.setHeaders

if (setHeaders !== undefined && typeof setHeaders !== 'function') {
return next(new TypeError('The `setHeaders` option must be a function'))
throw new TypeError('The `setHeaders` option must be a function')
}

@@ -27,3 +28,3 @@

if (invalidDirListOpts) {
return next(invalidDirListOpts)
throw invalidDirListOpts
}

@@ -44,7 +45,11 @@

function pumpSendToReply (request, reply, pathname, rootPath) {
function pumpSendToReply (request, reply, pathname, rootPath, rootPathOffset = 0) {
const options = Object.assign({}, sendOptions)
if (rootPath) {
options.root = rootPath
if (Array.isArray(rootPath)) {
options.root = rootPath[rootPathOffset]
} else {
options.root = rootPath
}
}

@@ -115,2 +120,8 @@

}
// root paths left to try?
if (Array.isArray(rootPath) && rootPathOffset < (rootPath.length - 1)) {
return pumpSendToReply(request, reply, pathname, rootPath, rootPathOffset + 1)
}
return reply.callNotFound()

@@ -160,3 +171,3 @@ }

fastify.get(prefix + '*', routeOpts, function (req, reply) {
pumpSendToReply(req, reply, '/' + req.params['*'])
pumpSendToReply(req, reply, '/' + req.params['*'], sendOptions.root)
})

@@ -172,13 +183,13 @@ if (opts.redirect === true && prefix !== opts.prefix) {

const globPattern = typeof opts.wildcard === 'string' ? opts.wildcard : '**/*'
glob(path.join(sendOptions.root, globPattern), { nodir: true }, function (err, files) {
if (err) {
return next(err)
}
async function addGlobRoutes (rootPath) {
const files = await globPromise(path.join(rootPath, globPattern), { nodir: true })
const indexDirs = new Set()
const indexes = typeof opts.index === 'undefined' ? ['index.html'] : [].concat(opts.index || [])
for (let file of files) {
file = file.replace(sendOptions.root.replace(/\\/g, '/'), '').replace(/^\//, '')
file = file.replace(rootPath.replace(/\\/g, '/'), '').replace(/^\//, '')
const route = encodeURI(prefix + file).replace(/\/\//g, '/')
fastify.get(route, routeOpts, function (req, reply) {
pumpSendToReply(req, reply, '/' + file)
pumpSendToReply(req, reply, '/' + file, rootPath)
})

@@ -190,2 +201,3 @@

}
indexDirs.forEach(function (dirname) {

@@ -196,3 +208,3 @@ const pathname = dirname + (dirname.endsWith('/') ? '' : '/')

fastify.get(pathname, routeOpts, function (req, reply) {
pumpSendToReply(req, reply, file)
pumpSendToReply(req, reply, file, rootPath)
})

@@ -202,15 +214,15 @@

fastify.get(pathname.replace(/\/$/, ''), routeOpts, function (req, reply) {
pumpSendToReply(req, reply, file.replace(/\/$/, ''))
pumpSendToReply(req, reply, file.replace(/\/$/, ''), rootPath)
})
}
})
next()
})
}
// return early to avoid calling next afterwards
return
if (Array.isArray(sendOptions.root)) {
await Promise.all(sendOptions.root.map(addGlobRoutes))
} else {
await addGlobRoutes(sendOptions.root)
}
}
}
next()
}

@@ -220,9 +232,30 @@

if (rootPath === undefined) {
return new Error('"root" option is required')
throw new Error('"root" option is required')
}
if (Array.isArray(rootPath)) {
if (!rootPath.length) { throw new Error('"root" option array requires one or more paths') }
if ([...new Set(rootPath)].length !== rootPath.length) {
throw new Error('"root" option array contains one or more duplicate paths')
}
// check each path and fail at first invalid
rootPath.map(path => checkPath(fastify, path))
return
}
if (typeof rootPath === 'string') {
return checkPath(fastify, rootPath)
}
throw new Error('"root" option must be a string or array of strings')
}
function checkPath (fastify, rootPath) {
if (typeof rootPath !== 'string') {
return new Error('"root" option must be a string')
throw new Error('"root" option must be a string')
}
if (path.isAbsolute(rootPath) === false) {
return new Error('"root" option must be an absolute path')
throw new Error('"root" option must be an absolute path')
}

@@ -240,7 +273,7 @@

return e
throw e
}
if (pathStat.isDirectory() === false) {
return new Error('"root" option must point to a directory')
throw new Error('"root" option must point to a directory')
}

@@ -247,0 +280,0 @@ }

{
"name": "fastify-static",
"version": "3.3.1",
"version": "3.4.0",
"description": "Plugin for serving static files as fast as possible.",

@@ -5,0 +5,0 @@ "main": "index.js",

@@ -62,2 +62,5 @@ # fastify-static

You can also provide an array of directories containing files to serve.
This is useful for serving multiple static directories under a single prefix. Files are served in a "first found, first served" manner, so the order in which you list the directories is important. For best performance, you should always list your main asset directory first. Duplicate paths will raise an error.
#### `prefix`

@@ -64,0 +67,0 @@

@@ -45,1 +45,13 @@ import fastify from 'fastify'

})
const multiRootAppWithImplicitHttp = fastify()
options.root = ['']
multiRootAppWithImplicitHttp
.register(fastifyStatic, options)
.after(() => {
multiRootAppWithImplicitHttp.get('/', (request, reply) => {
reply.sendFile('some-file-name')
})
})

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc