Scripting a simple nodejs server

This post covers scripting a simple node.js server from scratch. It’s easy, but deceivingly powerful.

We’ll use ES6 style javascript, HTTPS (with a self signed certificate), a live reloading server, and serve responses from an external JSON file.

What’s it for?

If you’ve got some kind of moving target (a versioned API, a usage restricted API, the API isn’t designed yet, an API with clunky authentication) it can drastically speed up your front-end development to have a quick nodejs server running to serve back JSON responses.

This is a two part project, the other side collects and stores responses from the real API in JSON files.

Initial setup

Since it’s a nodejs project, we need a package.json to store our dependencies and project info. Run npm init to initialise the project and create the file.

npm init threw an error? You probably need to upgrade or install nodejs & npm, see this tutorial first.

npm init asks a few questions, tap enter until it’s done. You’ll have a bare package.json file in your project.

Create an index.js file, and enter the following code: console.log("Works!");

Set up live reloading

We’re going to use live reloading from the start – our server will restart anytime we make a change. We use nodemon for this. Make sure you’ve got nodemon installed globally by running npm install -g nodemon

Generating self signed certificates

Next we need to generate some self signed certs that our https server will use. These are useful only for development.

openssl req -nodes -new -x509 -keyout server.key -out server.cert

Again it’ll ask a few questions, enter through it quickly. You should have a server.cert and a server.key in your project folder now.

Running the script the first time

In package.json, add a “start” key to the “scripts” object with value “nodemon index.js”

Your package.json should look like this:

{
  "name": "nodejs-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Run npm start to see the message “Works!” from above. Leave the script running.

If you get an error here, read it carefully and google the error. You’ll likely just be missing a library you need.

Now we’ll butcher that index.js file quickly to be a https server.

Setting up the nodejs server

Empty the file, and add the following

Import our https server library and the filesystem library (to read the certs). We need

const https = require('https');
const fs = require('fs');
const url = require('url');

Add the port in use, and a simple request handler.

const port = 3000;
const requestHandler = (request, response) => {
    // do something with the request here.
    console.log("Request received");
    response.end("Hello!");
};

Create the https server, and connect requests to the handler.

const server = https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
}, requestHandler);

Tell the server to listen for responses.

server.listen(port, (err) => {
    if (err) {
        return console.log('Error occurred.', err)
    }

    console.log(`server is listening on ${port}, https`)
})

When you’re saving index.js, you should notice the server repeatedly restarting. It’s ready for a request now!

If you used port 3000 above, you should be able to visit https://localhost:3000/ to see a response generated by requestHandler.

You’ll receive a security notice about your self signed certificates, continue past this.

Great! It’s working.

Sending back JSON from a file

To make this server useful, we need to connect it to some real world data.

For this demo, I borrowed books.json and dropped it in my responses.json file.

Download responses.json from here and drop it in your project.

If our test user visits https://localhost:3000/books, we want to serve him up the JSON stored in the ‘books’ key of the responses.json file. Change requestHandler to do this now:

const requestHandler = (request, response) => {
    // do something with the request here.
    console.log("Request received to " + request.url);

    switch (request.url) {
        case "/books":
            fs.readFile("./responses.json", function (err, contents) {
                let data = JSON.parse(contents);
                response.end(JSON.stringify(data.books));
            });
            break;
        case "/":
            response.end("Hello!");
            break;
        default:
            response.writeHead(404);
            response.end("Page not found.");
            break;
    }
};

To test, visit these 3 URLS. The first should return a JSON list of books, the second ‘Hello’, and the third a 404 error.
https://localhost:3000/books
https://localhost:3000/
https://localhost:3000/movies

Project files

The nodejs server in it’s finished state is available from github here. If you have any difficulties getting the project up and running, please let me know.