Update 14/03/2018:

Thanks to a pull request to my example repository by Francisco Presencia, the creator of Server.js, he explains that my original example can actually be cut down to a single line of code.

Server.js already contains the static middleware from Express so there is no need to include and configure the server manually. Server.js assumes that you want to serve static files from a directory called public/ in your project, in which case you can simply create the server as:

require('server')();

If you would like to serve the static files from a different directory, such as the root directory, as in my case you can simply pass a public configuration option when initializing the server. For example:

require('server')({ public: '.' });

This highlights how Server.js is even simpler to use than I assumed.


Server.js is a node based server that is based on Express.js but provides you with an even easier interface to write your server with.

As server.js was only recently released, I was trying to find a tutorial on how to serve a directory of static files but could not find one. After reading the documentation, I noticed that since Server.js is built on express, you can use express middlewares out of the box. Since Express already has a express.static() method, I noitced that I could use this to serve static files as I wanted.

The example server is very basic, it simply serves all files in the current directory.

First of all, I import server and express:

const server = require('server');
const express = require('express');

Next I import the modern method from server.utils that allows us to attach Express middleware to our server:

const { modern } = server.utils;

I then call the express.static middleware, and pass it to modern:

const middleware = modern(express.static('./'));

Finally, I start the server and pass the static middleware:

server(middleware);

The final server is only 7 lines long:

const server = require('server');
const express = require('express');
const { modern } = server.utils;

const middleware = modern(express.static('./'));

server(middleware);

You can test this by writing this to a file called server.js and calling it with node server.js. The server will then be running at: http://localhost:3000/.

If you then write an index.html file in the same directory, it will be served when visiting this address in your browser.

For full example code, please visit this repo: https://github.com/BlakeSimpson/serverjs-static-files