send vs serve-static vs koa-static
Node.js Static File Serving Libraries Comparison
1 Year
sendserve-statickoa-staticSimilar Packages:
What's Node.js Static File Serving Libraries?

These libraries are designed to serve static files in a Node.js environment, providing a way to efficiently deliver files such as HTML, CSS, JavaScript, images, and other resources over HTTP. They handle file serving with various features like caching, content negotiation, and directory listing, making it easier for developers to integrate static file serving into their applications without having to write custom code from scratch.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
send40,263,24380448.5 kB196 months agoMIT
serve-static37,806,7961,40525.4 kB176 months agoMIT
koa-static855,6811,142-87 years agoMIT
Feature Comparison: send vs serve-static vs koa-static

Framework Compatibility

  • send:

    send is framework-agnostic, allowing it to be used in any Node.js application. It can be integrated into various frameworks or used standalone, providing flexibility in its usage.

  • serve-static:

    serve-static is tailored for Express.js and similar frameworks, making it easy to integrate into existing Express applications. It utilizes the connect middleware stack, ensuring compatibility with Express's routing and middleware features.

  • koa-static:

    koa-static is specifically designed for Koa, leveraging its middleware architecture and async capabilities. It is optimized for Koa applications, ensuring smooth integration and performance.

Caching and Performance

  • send:

    send provides options for caching and streaming files, allowing developers to optimize performance based on their application's needs. It can handle large files efficiently by streaming them to the client, reducing memory usage.

  • serve-static:

    serve-static includes built-in support for caching via cache-control headers and offers options for setting custom cache durations. It is designed to serve static files quickly and efficiently, leveraging Express's middleware capabilities.

  • koa-static:

    koa-static supports caching through the use of cache-control headers, allowing browsers to cache static assets for improved performance. It also supports conditional GET requests, which can reduce bandwidth usage by serving files only when they have changed.

Error Handling

  • send:

    send offers robust error handling, providing detailed error messages and status codes for various scenarios, such as file not found or permission denied. This makes it easier for developers to debug issues related to file serving.

  • serve-static:

    serve-static includes error handling for missing files and other issues, returning standard HTTP error responses. It integrates well with Express's error handling middleware, allowing for consistent error management across the application.

  • koa-static:

    koa-static provides basic error handling for file serving, returning appropriate HTTP status codes when files are not found or inaccessible. It allows developers to customize error responses if needed.

Customization

  • send:

    send offers extensive customization options, including the ability to set headers, customize error responses, and control how files are served. This makes it suitable for applications with specific requirements regarding file serving.

  • serve-static:

    serve-static provides several options for customization, such as setting the root directory, configuring cache settings, and enabling directory listing. It allows developers to tailor the behavior of static file serving to fit their application's needs.

  • koa-static:

    koa-static allows for some customization options, such as setting the root directory for serving files and configuring cache settings. However, its primary focus is on simplicity and ease of use within Koa applications.

Ease of Use

  • send:

    send is also easy to use, with a simple API that allows developers to serve files with just a few lines of code. Its flexibility makes it accessible for various use cases, whether in a framework or standalone.

  • serve-static:

    serve-static is designed for ease of use within Express applications, providing a simple API for serving static files. Its widespread adoption means there are many resources and examples available for developers.

  • koa-static:

    koa-static is straightforward to use, requiring minimal configuration to get started. Its integration with Koa's middleware system makes it easy to set up and serve static files quickly.

How to Choose: send vs serve-static vs koa-static
  • send:

    Choose send if you need a lightweight and flexible solution for serving files in a variety of Node.js environments. It offers fine-grained control over file serving, including options for streaming, caching, and handling errors, making it suitable for both small and large applications.

  • serve-static:

    Choose serve-static if you are using Express.js or a similar framework and want a well-established solution that is easy to set up and use. It is built on top of the connect middleware and provides robust features for serving static files with support for caching and customizable options.

  • koa-static:

    Choose koa-static if you are using the Koa framework and need a middleware specifically designed for it. It integrates seamlessly with Koa's async/await syntax and provides a simple way to serve static files with support for caching and conditional requests.

README for send

send

NPM Version NPM Downloads Linux Build Windows Build Test Coverage

Send is a library for streaming files from the file system as a http response supporting partial responses (Ranges), conditional-GET negotiation (If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework.

Looking to serve up entire folders mapped to URLs? Try serve-static.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install send

API

var send = require('send')

send(req, path, [options])

Create a new SendStream for the given path to send to a res. The req is the Node.js HTTP request and the path is a urlencoded path to send (urlencoded, not the actual file-system path).

Options

acceptRanges

Enable or disable accepting ranged requests, defaults to true. Disabling this will not send Accept-Ranges and ignore the contents of the Range request header.

cacheControl

Enable or disable setting Cache-Control response header, defaults to true. Disabling this will ignore the immutable and maxAge options.

dotfiles

Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny").

  • 'allow' No special treatment for dotfiles.
  • 'deny' Send a 403 for any request for a dotfile.
  • 'ignore' Pretend like the dotfile does not exist and 404.

The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot, for backward-compatibility.

end

Byte offset at which the stream ends, defaults to the length of the file minus 1. The end is inclusive in the stream, meaning end: 3 will include the 4th byte in the stream.

etag

Enable or disable etag generation, defaults to true.

extensions

If a given file doesn't exist, try appending one of the given extensions, in the given order. By default, this is disabled (set to false). An example value that will serve extension-less HTML files: ['html', 'htm']. This is skipped if the requested file already has an extension.

immutable

Enable or disable the immutable directive in the Cache-Control response header, defaults to false. If set to true, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.

index

By default send supports "index.html" files, to disable this set false or to supply a new index pass a string or an array in preferred order.

lastModified

Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value.

maxAge

Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module.

root

Serve files relative to path.

start

Byte offset at which the stream starts, defaults to 0. The start is inclusive, meaning start: 2 will include the 3rd byte in the stream.

Events

The SendStream is an event emitter and will emit the following events:

  • error an error occurred (err)
  • directory a directory was requested (res, path)
  • file a file was requested (path, stat)
  • headers the headers are about to be set on a file (res, path, stat)
  • stream file streaming has started (stream)
  • end streaming has completed

.pipe

The pipe method is used to pipe the response into the Node.js HTTP response object, typically send(req, path, options).pipe(res).

Error-handling

By default when no error listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc.

Caching

It does not perform internal caching, you should use a reverse proxy cache such as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;).

Debugging

To enable debug() instrumentation output export DEBUG:

$ DEBUG=send node app

Running tests

$ npm install
$ npm test

Examples

Serve a specific file

This simple example will send a specific file to all requests.

var http = require('http')
var send = require('send')

var server = http.createServer(function onRequest (req, res) {
  send(req, '/path/to/index.html')
    .pipe(res)
})

server.listen(3000)

Serve all files from a directory

This simple example will just serve up all the files in a given directory as the top-level. For example, a request GET /foo.txt will send back /www/public/foo.txt.

var http = require('http')
var parseUrl = require('parseurl')
var send = require('send')

var server = http.createServer(function onRequest (req, res) {
  send(req, parseUrl(req).pathname, { root: '/www/public' })
    .pipe(res)
})

server.listen(3000)

Custom file types

var extname = require('path').extname
var http = require('http')
var parseUrl = require('parseurl')
var send = require('send')

var server = http.createServer(function onRequest (req, res) {
  send(req, parseUrl(req).pathname, { root: '/www/public' })
    .on('headers', function (res, path) {
      switch (extname(path)) {
        case '.x-mt':
        case '.x-mtt':
          // custom type for these extensions
          res.setHeader('Content-Type', 'application/x-my-type')
          break
      }
    })
    .pipe(res)
})

server.listen(3000)

Custom directory index view

This is an example of serving up a structure of directories with a custom function to render a listing of a directory.

var http = require('http')
var fs = require('fs')
var parseUrl = require('parseurl')
var send = require('send')

// Transfer arbitrary files from within /www/example.com/public/*
// with a custom handler for directory listing
var server = http.createServer(function onRequest (req, res) {
  send(req, parseUrl(req).pathname, { index: false, root: '/www/public' })
    .once('directory', directory)
    .pipe(res)
})

server.listen(3000)

// Custom directory handler
function directory (res, path) {
  var stream = this

  // redirect to trailing slash for consistent url
  if (!stream.hasTrailingSlash()) {
    return stream.redirect(path)
  }

  // get directory list
  fs.readdir(path, function onReaddir (err, list) {
    if (err) return stream.error(err)

    // render an index for the directory
    res.setHeader('Content-Type', 'text/plain; charset=UTF-8')
    res.end(list.join('\n') + '\n')
  })
}

Serving from a root directory with custom error-handling

var http = require('http')
var parseUrl = require('parseurl')
var send = require('send')

var server = http.createServer(function onRequest (req, res) {
  // your custom error-handling logic:
  function error (err) {
    res.statusCode = err.status || 500
    res.end(err.message)
  }

  // your custom headers
  function headers (res, path, stat) {
    // serve all files for download
    res.setHeader('Content-Disposition', 'attachment')
  }

  // your custom directory handling logic:
  function redirect () {
    res.statusCode = 301
    res.setHeader('Location', req.url + '/')
    res.end('Redirecting to ' + req.url + '/')
  }

  // transfer arbitrary files from within
  // /www/example.com/public/*
  send(req, parseUrl(req).pathname, { root: '/www/public' })
    .on('error', error)
    .on('directory', redirect)
    .on('headers', headers)
    .pipe(res)
})

server.listen(3000)

License

MIT