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