• Stars
    star
    376
  • Rank 113,810 (Top 3 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 12 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A node module for serving static files. Does etags, caching, etc.

st

Travis Status

A module for serving static files. Does etags, caching, etc.

USAGE

Here are some very simple usage examples.

Just serve the files in the cwd at the root of the http server url:

const st = require('st')
const http = require('http')

http.createServer(
  st(process.cwd())
).listen(1337)

Serve the files in static under the /static url. Otherwise do a different thing:

const path = require('path')
const mount = st({ path: path.join(__dirname, '/static'), url: '/static' })

http.createServer((req, res) => {
  const stHandled = mount(req, res)
  if (stHandled)
    return
  else
    res.end('this is not a static file')
}).listen(1338)

The same sort of thing, but using an express middleware style:

const path = require('path')
const mount = st({ path: path.join(__dirname, '/static'), url: '/static' })

http.createServer((req, res) => {
  mount(req, res, () => res.end('this is not a static file'))
}).listen(1339)

Serve the files in static under the / url, but only if not some doing other thing:

const path = require('path')
const mount = st({ path: path.join(__dirname, '/static'), url: '/' })

http.createServer((req, res) => {
  if (shouldDoThing(req)) {
    doTheThing(req, res)
  } else {
    mount(req, res)
  }
}).listen(1340)

Serve the files in static under the / url, but don't serve a 404 if the file isn't found, so that the rest of the app can handle it:

const path = require('path')
const mount = st({ path: path.join(__dirname, '/static'), url: '/', passthrough: true})

http.createServer((req, res) => {
  mount(req, res, () => res.end('this is not a static file'))
}).listen(1341)

Serve the files with CORS enabled, to serve static files to any domain:

http.createServer(
  st({
   path: process.cwd(),
   cors: true
  })
).listen(1337)

Pass some options to the st function, and it returns a handler function.

That handler function will return true if it handles the static request, or false if it doesn't. (This is so that you can only serve static files if they're in /static for example.)

Here are some options if you want to configure stuff. All of these are optional except path which tells it where to get stuff from.

If you pass a string instead of an object, then it'll use the string as the path.

If you don't specify a url, then it'll mount on the '/' url, so st({ path: './static/' }) will try to serve ./static/foo.html when the user goes to http://example.com/foo.html. (Note: This behavior changed in st 0.2.0.)

Here are all the options described with their defaults values and a few possible settings you might choose to use:

const st = require('st')
const mount = st({
  path: 'resources/static/', // resolved against the process cwd
  url: 'static/', // defaults to '/'

  cache: { // specify cache:false to turn off caching entirely
    fd: {
      max: 1000, // number of fd's to hang on to
      maxAge: 1000*60*60, // amount of ms before fd's expire
    },

    stat: {
      max: 5000, // number of stat objects to hang on to
      maxAge: 1000 * 60, // number of ms that stats are good for
    },

    content: {
      max: 1024*1024*64, // how much memory to use on caching contents
      maxAge: 1000 * 60 * 10, // how long to cache contents for
                              // if `false` does not set cache control headers
      cacheControl: 'public, max-age=600' // to set an explicit cache-control
                                          // header value
    },

    index: { // irrelevant if not using index:true
      max: 1024 * 8, // how many bytes of autoindex html to cache
      maxAge: 1000 * 60 * 10, // how long to store it for
    },

    readdir: { // irrelevant if not using index:true
      max: 1000, // how many dir entries to cache
      maxAge: 1000 * 60 * 10, // how long to cache them for
    }
  },

  // indexing options
  index: true, // auto-index, the default
  index: 'index.html', // use 'index.html' file as the index
  index: false, // return 404's for directories

  dot: false, // default: return 403 for any url with a dot-file part
  dot: true, // allow dot-files to be fetched normally

  passthrough: true, // calls next/returns instead of returning a 404 error
  passthrough: false, // returns a 404 when a file or an index is not found

  gzip: true, // default: compresses the response with gzip compression
  gzip: false, // does not compress the response, even if client accepts gzip

  cors: false, // default: static assets not accessible from other domains
  cors: true, // static assets can be accessed from any domain
})

// with bare node.js
http.createServer((req, res) => {
  if (mount(req, res)) return // serving a static file
  myCustomLogic(req, res)
}).listen(PORT)

// with express
app.use(mount)
// or
app.route('/static/:fooblz', (req, res, next) => {
  mount(req, res, next) // will call next() if it doesn't do anything
})

On the command line:

$ st -h
st
Static file server in node

Options:

-h --help             Show this help

-p --port PORT        Listen on PORT (default=1337)

-H --host HOST        Bind address HOST (default=*)

-l --localhost        Same as "--host localhost"

-d --dir DIRECTORY    Serve the contents of DIRECTORY (default=cwd)

-u --url MOUNTURL     Serve the contents at MOUNTURL mount path (default=/)

-i --index [INDEX]    Use the specified INDEX filename as the result
                      when a directory is requested.  Set to "true"
                      to turn autoindexing on, or "false" to turn it
                      off.  If no INDEX is provided, then it will turn
                      autoindexing on.  (default=true)

-ni --no-index        Same as "--index false"

-. --dot [DOT]        Allow .files to be served.  Set to "false" to
                      disable.

-n. --no-dot          Same as "--dot false"

-co --cors            Enable CORS to serve files to any domain.

-nc --no-cache        Turn off all caching.

-a --age AGE          Max age (in ms) of cache entries.

Range Requests

Range requests are not supported.

I'd love a patch to add support for them, but the spec is kind of confusing, and it's not always a clear win if you're not serving very large files, so it should come with some very comprehensive tests.

Thankfully, as far as I can tell, it's always safe to serve the entire file to a request with a range header, so st does behave correctly, if not ideally in those situations. It'd be great to be able to do the better thing if the contents are cached, but still serve the full file if it's not in cache (so that it can be cached for subsequent requests).

Memory Caching

To make things go as fast as possible, it is a good idea to set the cache limits as high as you can afford, given the amount of memory on your server. Serving buffers out of process memory will generally always be faster than hitting the file system.

Client Caching

An etag header and last-modified will be attached to every request. If presented with an if-none-match or if-modified-since, then it'll return a 304 in the appropriate conditions.

The etag is generated based on the dev, ino, and last modified date. Stat results are cached.

Compression

If the request header claims to enjoy gzip encoding, and the filename does not end in '.gz' or '.tgz', then the response will be gzipped.

Gzipped bytes are not included in the calculation of cache sizes, so this utility will use a bit more memory than the cache.content.max and cache.index.max bytes would seem to allow. This will be less than double, and usually insignificant for normal web assets, but is important to consider if memory is at a premium.

Gzip compression can be disabled by setting gzip: false on the options passed into st(). This is useful if your application already handles gzipping responses by other means.

Filtering Output

If you want to do some fancy stuff to the file before sending it, you can attach a res.filter = myFilterStream thing to the response object before passing it to the mount function.

This is useful if you want to get the benefits of caching and gzipping and such, but serve stylus files as css, for example.

Security Status

Versions prior to 0.2.5 did not properly prevent folder traversal. Literal dots in a path were resolved out, but url encoded dots were not. Thus, a request like /%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd would leak sensitive data from the server.

As of version 0.2.5, any '/../' in the request path, urlencoded or not, will be replaced with '/'. If your application depends on url traversal, then you are encouraged to please refactor so that you do not depend on having .. in url paths, as this tends to expose data that you may be surprised to be exposing.

Consider using the --localhost setting if you don't want other people on your local network to read the files served by the command line server. This may become the default in a future major version.

More Repositories

1

node-glob

glob functionality for node.js
TypeScript
8,123
star
2

rimraf

A `rm -rf` util for nodejs
JavaScript
5,309
star
3

node-lru-cache

A fast cache that automatically deletes the least recently used items
TypeScript
4,844
star
4

minimatch

a glob matcher in javascript
JavaScript
3,074
star
5

github

Just a place to track issues and feature requests that I have for github
2,209
star
6

nave

Virtual Environments for Node
Shell
1,580
star
7

node-graceful-fs

fs with incremental backoff on EMFILE
JavaScript
1,267
star
8

sax-js

A sax style parser for JS
JavaScript
1,046
star
9

tshy

JavaScript
847
star
10

node-tar

tar for node
JavaScript
755
star
11

inherits

Easy simple tiny inheritance in JavaScript
JavaScript
352
star
12

cluster-master

Take advantage of node built-in cluster module behavior
JavaScript
276
star
13

minipass

A stream implementation that does more by doing less
TypeScript
246
star
14

once

Run a function exactly one time
JavaScript
216
star
15

yallist

Yet Another Linked List
JavaScript
198
star
16

server-destroy

When close() is just not enough
JavaScript
184
star
17

ttlcache

TypeScript
155
star
18

semicolons

When you require("semicolons"), THEY ARE REQUIRED.
JavaScript
145
star
19

slide-flow-control

A flow control library that fits in a slideshow
JavaScript
134
star
20

treeverse

Walk any kind of tree structure depth- or breadth-first. Supports promises and advanced map-reduce operations with a very small API.
JavaScript
130
star
21

multipart-js

JavaScript
123
star
22

reading-list

a list of books I recommend
121
star
23

node-touch

touch(1) for node
JavaScript
121
star
24

catcher

TypeScript
119
star
25

async-cache

Cache your async lookups and don't fetch the same thing more than necessary.
JavaScript
119
star
26

core-util-is

The util.is* functions from Node core
JavaScript
98
star
27

dezalgo

Contain async insanity so that the dark pony lord doesn't eat souls
JavaScript
89
star
28

github-flavored-markdown

Deprecated. Use marked instead.
JavaScript
79
star
29

minizlib

A smaller, faster, zlib stream built on http://npm.im/minipass and Node.js's zlib binding.
JavaScript
71
star
30

node-bench

JavaScript
71
star
31

free-as-in-hugs-license

A (Not OSI-Approved) software license you may use if you wish
70
star
32

sigmund

Quick and dirty psychoanalysis for objects
JavaScript
67
star
33

inflight

Add callbacks to requests in flight to avoid async duplication
JavaScript
66
star
34

fast-list

A fast O(1) push/pop/shift/unshift thing
JavaScript
66
star
35

gist-cli

A gist cli client written in Node
JavaScript
64
star
36

dotfiles

My Dot Files
Shell
63
star
37

wrappy

Callback wrapping utility
JavaScript
56
star
38

block-stream

A stream of fixed-size blocks
JavaScript
52
star
39

isexe

Minimal module to check if a file is executable.
TypeScript
48
star
40

.vim

My vim settings
Vim Script
47
star
41

jackspeak

A very strict and proper argument parser.
TypeScript
44
star
42

char-spinner

Put a little spinner on process.stderr, as unobtrusively as possible.
JavaScript
43
star
43

st-example

an example of serving static files easily in node using the st module
JavaScript
40
star
44

templar

A lightweight template thing for node http servers
JavaScript
37
star
45

nosync

Prevent sync functions in your node programs after first tick
JavaScript
37
star
46

use-strict

Makes all subsequent modules in Node get loaded in strict mode.
JavaScript
37
star
47

path-scurry

TypeScript
35
star
48

ssh-key-decrypt

Decrypt and encrypted ssh private keys
JavaScript
35
star
49

ejsgi

Like JSGI, but using streams.
JavaScript
35
star
50

node-eliza

A Robotic Rogerian Therapist, on IRC
JavaScript
34
star
51

natives

Do stuff with Node.js's native JavaScript modules
JavaScript
31
star
52

goosh

Front-end old-style terminal interface, for web services like those provided by Google and Yahoo.
JavaScript
31
star
53

simple-node-server

A simple fast node http server toolkit.
JavaScript
30
star
54

util-extend

Node's internal object extension function, for you!
JavaScript
30
star
55

chownr

Like `chown -R`
JavaScript
28
star
56

csrf-lite

CSRF protection utility for framework-free node sites.
JavaScript
28
star
57

chmodr

Like `chmod -R` in node
JavaScript
28
star
58

node-hexedit

hexadecimal editor in node
JavaScript
27
star
59

back-to-markdown.css

Turns any markdown editor into a WYSIWYG editor
CSS
26
star
60

node-async-simple

Multiply two numbers, slowly, on the thread pool.
C++
26
star
61

json-stringify-nice

Stringify an object sorting scalars before objects, and defaulting to 2-space indent
JavaScript
25
star
62

node-strict

Makes your Node programs strict about stuff when loaded
JavaScript
25
star
63

fs.realpath

Use node's fs.realpath, but fall back to the JS implementation if the native one fails
JavaScript
25
star
64

sock-daemon

TypeScript
24
star
65

promise-all-reject-late

Like Promise.all, but save rejections until all promises are resolved
JavaScript
24
star
66

promise-call-limit

Call an array of promise-returning functions, restricting concurrency to a specified limit.
TypeScript
24
star
67

node6-module-system-change

A demonstration of what changed in node 6's module loading logic
JavaScript
24
star
68

color-support

A module which will endeavor to guess your terminal's level of color support.
JavaScript
24
star
69

polite-json

TypeScript
23
star
70

ircretary

A note-taking IRC bot
JavaScript
23
star
71

yamlish

A parser for the yamlish format
JavaScript
22
star
72

fs-minipass

fs read and write streams based on minipass
JavaScript
21
star
73

pseudomap

Like `new Map` but for older JavaScripts
JavaScript
21
star
74

node-fuse

Fuse bindings for nodejs
21
star
75

slocket

A locking socket alternative to file-system mutex locks
JavaScript
21
star
76

proto-list

A list of objects bound by prototype chain
JavaScript
20
star
77

retry-until

A function that will keep running a function you give it as long as it throws for a period of time
JavaScript
20
star
78

node-srand

srand bindings for node - Seedable predictable pseudorandom number generator
C++
20
star
79

mutate-fs

Mutate the Node.js filesystem behavior for tests.
JavaScript
20
star
80

ryp

Featureless npm-package bundling.
Shell
19
star
81

filewatcherthing

a thing to watch a file and then run a command
JavaScript
19
star
82

gatsby-remark-tumble-media

A plugin for gatsby-transformer-remark to support photosets, video, and audio in markdown frontmatter.
JavaScript
19
star
83

sodn

SOcial DNodes
JavaScript
19
star
84

joyent-node-on-smart-example

A blog post.
JavaScript
18
star
85

error-page

Easily send errors in Node.js HTTP servers. Think like the `ErrorDocument` declarations in Apache config files.
JavaScript
17
star
86

_ify

an itty bitty curry utility
JavaScript
17
star
87

url-parse-as-address

Parse a URL assuming that it's http/https, even if protocol or // isn't present
JavaScript
17
star
88

http-https

A wrapper that chooses http or https for requests
JavaScript
17
star
89

perfalize

TypeScript
16
star
90

cssmin

A cross-platform regular-expression based minifier for CSS
16
star
91

duplex-passthrough

like a passthrough, but in both directions
JavaScript
16
star
92

mintee

a tiny module for piping an input to multiple output streams
JavaScript
16
star
93

create-isaacs

An npm init module to create modules like I do
JavaScript
16
star
94

tap-assert

An assert module that outputs tap result objects
JavaScript
16
star
95

domain-http-server

A module thingie to use domains in Express or Restify or just regular HTTP servers
JavaScript
15
star
96

fs-readstream-seek

A fs.ReadStream that supports seeking to arbtrary locations within a file.
JavaScript
15
star
97

canonical-host

Node module to redirect users to the canonical hostname for your site.
JavaScript
15
star
98

mcouch

Put your CouchDB in Manta, attachments and docs and all
JavaScript
14
star
99

hardhttps

Slightly hardened https for node
JavaScript
14
star
100

exit-code

`process.exitCode` behavior back-ported from io.js and Node.js 0.12+
JavaScript
14
star