• Stars
    star
    2,171
  • Rank 21,240 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 14 years ago
  • Updated 3 months ago

Reviews

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

Repository Details

rfc 2616 compliant HTTP static-file server module, with built-in caching.

node-static

Node.js CI status

a simple, rfc 2616 compliant file streaming module for node

node-static understands and supports conditional GET and HEAD requests. node-static was inspired by some of the other static-file serving modules out there, such as node-paperboy and antinode.

Installation

$ npm install node-static

Set-up

ESM

import {Server, version, mime} from 'node-static';

// OR:
// import * as statik from 'node-static';

CommonJS

const statik = require('node-static');

Usage

//
// Create a node-static server instance to serve the './public' folder
//
const file = new statik.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    }).resume();
}).listen(8080);

API

Creating a node-static Server

Creating a file server instance is as simple as:

new statik.Server();

This will serve files in the current directory. If you want to serve files in a specific directory, pass it as the first argument:

new statik.Server('./public');

You can also specify how long the client is supposed to cache the files node-static serves:

new statik.Server('./public', { cache: 3600 });

This will set the Cache-Control header, telling clients to cache the file for an hour. This is the default setting.

Serving files under a directory

To serve files under a directory, simply call the serve method on a Server instance, passing it the HTTP request and response object:

const statik = require('node-static');

var fileServer = new statik.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
}).listen(8080);

Serving specific files

If you want to serve a specific file, like an error page for example, use the serveFile method:

fileServer.serveFile('/error.html', 500, {}, request, response);

This will serve the error.html file, from under the file root directory, with a 500 status code. For example, you could serve an error page, when the initial request wasn't found:

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response, function (e, res) {
            if (e && (e.status === 404)) { // If the file wasn't found
                fileServer.serveFile(
                    '/not-found.html', 404, {}, request, response
                );
            }
        });
    }).resume();
}).listen(8080);

More on intercepting errors bellow.

Intercepting errors & Listening

An optional callback can be passed as last argument, it will be called every time a file has been served successfully, or if there was an error serving the file:

const statik = require('node-static');

const fileServer = new statik.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response, function (err, result) {
            if (err) { // There was an error serving the file
                console.error(
                    "Error serving " + request.url + " - " + err.message
                );

                // Respond to the client
                response.writeHead(err.status, err.headers);
                response.end();
            }
        });
    }).resume();
}).listen(8080);

Note that if you pass a callback, and there is an error serving the file, node-static will not respond to the client. This gives you the opportunity to re-route the request, or handle it differently.

For example, you may want to interpret a request as a static request, but if the file isn't found, send it to an application.

If you only want to listen for errors, you can use event listeners:

fileServer.serve(request, response).addListener('error', function (err) {
    console.error("Error serving " + request.url + " - " + err.message);
});

With this method, you don't have to explicitly send the response back, in case of an error.

Options when creating an instance of Server

cache (Default: 3600)

Sets the Cache-Control header.

example: { cache: 7200 } will set the max-age for all files to 7200 seconds example: { cache: {'**/*.css': 300}} will set the max-age for all CSS files to 5 minutes.

Passing a number will set the cache duration to that number of seconds. Passing false will disable the Cache-Control header. Passing a object with minimatch glob pattern keys and number values will set cache max-age for any matching paths.

serverInfo (Default: node-static/{version})

Sets the Server header.

example: { serverInfo: "myserver" }

headers (Default: {})

Sets response headers.

example: { headers: { 'X-Hello': 'World!' } }

gzip (Default: false)

Enable support for sending compressed responses. This will enable a check for a file with the same name plus '.gz' in the same folder. If the compressed file is found and the client has indicated support for gzip file transfer, the contents of the .gz file will be sent in place of the uncompressed file along with a Content-Encoding: gzip header to inform the client the data has been compressed.

example: { gzip: true } example: { gzip: /^\/text/ }

Passing true will enable this check for all files. Passing a RegExp instance will only enable this check if the content-type of the respond would match that RegExp using its test() method.

indexFile (Default: index.html)

Choose a custom index file when serving up directories.

example: { indexFile: "index.htm" }

defaultExtension (Default: null)

Choose a default extension when serving files. A request to '/myFile' would check for a myFile folder (first) then a myFile.html (second).

example: { defaultExtension: "html" }

Command Line Interface

node-static also provides a CLI.

--port, -p          TCP port at which the files will be served                        [default: 8080]
--host-address, -a  the local network interface at which to listen                    [default: "127.0.0.1"]
--cache, -c         "Cache-Control" header setting, defaults to 3600
--version, -v       node-static version
--headers, -H       additional headers (in JSON format)
--header-file, -f   JSON file of additional headers
--gzip, -z          enable compression (tries to serve file of same name plus '.gz')
--spa               Serve the content as a single page app by redirecting all
                    non-file requests to the index HTML file.
--indexFile, -i     Specify a custom index file when serving up directories.          [default: "index.html"]
--help, -h          display this help message

Example Usage

# serve up the current directory
$ static
serving "." at http://127.0.0.1:8080

# serve up a different directory
$ static public
serving "public" at http://127.0.0.1:8080

# specify additional headers (this one is useful for development)
$ static -H '{"Cache-Control": "no-cache, must-revalidate"}'
serving "." at http://127.0.0.1:8080

# set cache control max age
$ static -c 7200
serving "." at http://127.0.0.1:8080

# expose the server to your local network
$ static -a 0.0.0.0
serving "." at http://0.0.0.0:8080

# show help message, including all options
$ static -h

More Repositories

1

rx

๐Ÿ‘พ Modern and minimalist pixel editor
Rust
2,920
star
2

toto

the 10 second blog-engine for hackers
Ruby
1,473
star
3

http-console

simple, intuitive HTTP REPL โ€” Speak HTTP like a local.
JavaScript
1,358
star
4

eyes.js

a customizable value inspector for node.js
JavaScript
342
star
5

journey

liberal JSON-only HTTP request routing for node.
JavaScript
321
star
6

nakamoto

Privacy-preserving Bitcoin light-client implementation in Rust
Rust
303
star
7

thingler

The amazingly simple-to-use, real-time, collaborative todo list!
JavaScript
296
star
8

dorothy

a basic template for toto, the blogging engine
Ruby
244
star
9

hijs

simple & fast javascript syntax highlighting for the browser
JavaScript
240
star
10

rgx.legacy

Modern mid-level 2D graphics library
Rust
194
star
11

popol

Minimal non-blocking I/O for Rust
Rust
157
star
12

neovim-fuzzy

Minimalistic fuzzy file finding for neovim
Vim Script
111
star
13

dotfiles

~cloudhead
Vim Script
100
star
14

mutter

the tiny command-line interface library with lots of style~
Ruby
80
star
15

resourcer

a resource-oriented object-relational mapper for document databases
JavaScript
58
star
16

pixelog

simple pixel tracking server
Go
56
star
17

node-syslog

a syslog-ng TCP client, with basic fault-tolerance.
JavaScript
32
star
18

koi

minimal task management for hackers
Ruby
31
star
19

nonempty

Correct by construction non-empty list
Rust
30
star
20

px

Superseded by `rx`
C
30
star
21

erlapp.template

minimal erlang/OTP rebar template
Erlang
29
star
22

styleguide

style-guide for various languages
27
star
23

shady.vim

Shady vim color-scheme for late night hacking
Vim Script
23
star
24

vargs

practical variable argument handling in node.js
JavaScript
22
star
25

neovim-ghcid

Provides instant haskell error feedback inside of neovim, via ghcid.
Vim Script
21
star
26

microserde

miniserde minus the dependencies
Rust
18
star
27

pilgrim

a JSON consuming JavaScript XHR client for the browser
JavaScript
15
star
28

nimbus

nimble, durable, document store
JavaScript
14
star
29

spell-correct

ruby implementation of Norvig's spell corrector
Ruby
12
star
30

node-crawler

http crawler โ€” (project under development)
JavaScript
12
star
31

arbre

a dynamic functional programming language experiment
C
10
star
32

rig.js

temporally extend an object's capabilities.
JavaScript
9
star
33

mrchat

micro chat client for the console, in c, with some tasteful ncurses
C
9
star
34

talker-plugins

A bunch of plugins for Talker (http://talkerapp.com)
JavaScript
9
star
35

node-provider

Manage HTTP content providers. It's 'Accept'-based routing, folks!
JavaScript
9
star
36

proto.js

prototype & other core extensions
JavaScript
8
star
37

github-unwatcher

Unwatch github repos
JavaScript
8
star
38

memoir

Self-describing, reflective parser combinators
Rust
7
star
39

spinsv

a stateless service runner inspired by runit
Haskell
7
star
40

avl-auth

An authenticated AVL+ tree implementation in Haskell
Haskell
6
star
41

bloomy

Bloom filter implementation in Rust
Rust
6
star
42

gogol

a bitmap drawing & animation library for Go
Go
6
star
43

cloudhead.io

This is my website.
CSS
5
star
44

prose

lightweight text to html parser, combining the best of Markdown with a hint of Textile
Ruby
5
star
45

s3web

scripts for publishing static sites to S3
Ruby
4
star
46

github-recommend

recommendation engine for github's 2009 contest
C
4
star
47

monsv

a service runner inspired by runsv
Go
3
star
48

diffraction

even stocks can be diffracted!
Ruby
3
star
49

melon

hybrid javascript/ruby micro app engine
Ruby
3
star
50

node-intro

intro to node.js presentation for montreal.js
JavaScript
3
star
51

cryptocurrency

Cryptocurrency library for Haskell
Haskell
2
star
52

golem

pre-forking HTTP server for node (old)
JavaScript
2
star
53

ghoul

your (node) deployment minion - a work in progress.
PHP
2
star
54

rx.cloudhead.io

CSS
2
star
55

birth

graceful linux system birthing
Vim Script
2
star
56

extender

handy extensions to keep your code cleanโ„ข
Ruby
2
star
57

sokol-gfx-rs

C
1
star
58

iohk-challenge

IOHK Haskell test
Haskell
1
star
59

a-file-uploader

JavaScript
1
star
60

rgx

2D Graphics Toolkit for Rust
Rust
1
star