, LLC.

A Simple Node Static  Server

Simple way to serve static HTML, images, stylesheets and scripts with Node.js

Serving static HTML, images, stylesheets and scripts with Node.js isn’t as out of the box as you might expect. Most developers coming from a PHP or Rails background might be surprise to find that you’ll need to configure a static file server in order to work with the everyday files that a normal web server can serve out of the box. Luckily, it’s really easy to setup a simple node static server with the following approach.

This tutorial assumes that you already have npm and node installed, and that you’re already working within a Node.js project directory, preferably one with a package.json file configured.

1. Install dependencies

Install the node-static module to get started with the following command: npm install --save node-static. If you don’t have a package.json file configured you can install using npm install node-static instead.

2. Create the server

Create a server.js file in your project’s root directory and add the following to it. If you’re extra lazy you can copy/paste the following HTML snippet into ./public/index.html as well to verify the static server is working.


 * Static HTTP Server
 * Create a static file server instance to serve files
 * and folder in the './public' folder

// modules
var static = require( 'node-static' ),
    port = 8080,
    http = require( 'http' );

// config
var file = new static.Server( './public', {
    cache: 3600,
    gzip: true
} );

// serve
http.createServer( function ( request, response ) {
    request.addListener( 'end', function () {
        file.serve( request, response );
    } ).resume();
} ).listen( port );


<!DOCTYPE html>
    <title>Simple, Static Node.js Server</title>
<h1>Simple, Static Node.js Server</h1>

3. Serve our files

Add a folder named public to your project, and add an index.html file in that directory. Start the server by running node server.js from the command-line. Be sure to change to your project directory before running this. Open your browser to localhost:8080, and boom you’re done.

That’s it! You should be all set with a simple node static server setup now. To give credit where it’s due, this setup is leveraging the wonderful node-static module.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 16 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.