serve-static
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
encodeurl | 1.0.2 | 3.18 kB | MIT | prod | |
escape-html | 1.0.3 | 1.87 kB | MIT | prod | |
parseurl | 1.3.3 | 3.86 kB | MIT | prod | |
send | 0.15.1 | 13.55 kB | MIT | prod | 3 1 1 |
The serve-static module in Node.js is a middleware used for serving static files. These files are served from a specific root directory. The file to be served is determined by the combination of req.url
with the provided root directory. If the file isn't found, instead of sending a 404 response, the module will call next()
to move on to the next middleware, thereby allowing for stacking and fall-backs.
In order to use serve-static, you first need to install it by running npm install serve-static
in your terminal. Once installed, you can require it in your application like this:
var serveStatic = require('serve-static')
Afterwards, you can set up the middleware to serve files from a specific directory. For example, to serve files from a directory named public
, use the code below:
// Serve up public/ftp folder
var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] })
Here, serve
is a function, which can be used with an HTTP Server object:
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')
var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] })
var server = http.createServer(function onRequest (req, res) {
serve(req, res, finalhandler(req, res))
})
server.listen(3000)
In this example, the server listens on port 3000, and files in the public/ftp
directory can be accessed by browsing to http://localhost:3000. The { index: ['index.html', 'index.htm'] }
option specifies that index.html
or index.htm
will be served when a request targets a directory.
The serve-static documentation is available in the README file on the GitHub project page. More in-depth details can be found directly on the GitHub repository for serve-static. By visiting the link, users can access comprehensive information about API usage, available options, and several code examples demonstrating how to use serve-static in various settings.