Skip to main content

Learning Node.js with Richard Astbury

I recently found myself a little side project which I decided I wanted to implement using Node.js. Although I did the Norfolk Developer’s Node.js workshop, it was quite a while ago and I don’t really remember much of it, so I asked Richard Astbury if he’d help me. Richard agreed and is writing a series of blog posts to help me learn. The first one explains how to create a Node.js project which uses the Express web framework. Below is my account of how I got on.

Richard’s instructions start from the point at which Node.js is installed. He then took me through creating a new directory for the application and installing Express:

mkdir nakedlogs
cd nakedlogs
npm install express

npm http GET https://registry.npmjs.org/express
...
express@4.13.3 node_modules/express
├── escape-html@1.0.2
├── merge-descriptors@1.0.0
├── array-flatten@1.1.1
├── cookie@0.1.3
├── utils-merge@1.0.0
├── cookie-signature@1.0.6
├── methods@1.1.1
├── path-to-regexp@0.1.7
├── range-parser@1.0.2
├── vary@1.0.1
├── fresh@0.3.0
├── etag@1.7.0
├── content-type@1.0.1
├── parseurl@1.3.0
├── content-disposition@0.5.0
├── serve-static@1.10.0
├── depd@1.0.1
├── qs@4.0.0
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
├── on-finished@2.3.0 (ee-first@1.1.1)
├── debug@2.2.0 (ms@0.7.1)
├── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.6)
├── accepts@1.2.13 (negotiator@0.5.3, mime-types@2.1.6)
└── send@0.13.0 (destroy@1.0.3, ms@0.7.1, statuses@1.2.1, mime@1.3.4, http-errors@1.3.1)

After installing Express I could see all the code in the new express directory in the node_modules directory, just as Richard said I would.

Next I needed to implement the obligatory ‘Hello World’, so I followed Richard’s instructions and created a server.js file in the root directory of the project:

// load the express package
var express = require('express');

// create an express application 
var app = express();

// handle GET requests at /
app.get('/', function(req, res){

  // respond with plain text
  res.send('hello world');
});

// start listening on port 8080
app.listen(8080);

It was really easy to get the application to run. All I had to do was enter:

node server.js

at the command line and then use a browser to go to

http://localhost:8080

to see the ‘Hello World’ message.

Richard suggested using npm init to create a package.js file. It was really easy to do:

npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (nakedlogs) 
version: (0.0.0) 
git repository: 
keywords: 
license: (BSD-2-Clause) 
About to write to /home/paul/dev/nakedlog/astbury/nakedlogs/package.json:

{
  "name": "nakedlogs",
  "version": "0.0.0",
  "description": "A remote logging web application",
  "main": "server.js",
  "dependencies": {
    "express": "~4.13.3"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "Naked Element Ltd.",
  "license": "BSD-2-Clause"
}

Is this ok? (yes) yes

Richard’s instructions finish at this point. However I like to see web applications running on the web and Heroku makes it really easy to do that (I know Richard is an Azure fan, but I haven't used that before).

Heroku uses a git repository that you deploy your code to, so the first thing I needed to do was get my project into a git repository, which means I needed a .gitignore file suitable for Node.js. A quick Google revealed that the following would do the trick:

# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules

Then it’s just a case of initialising git:

git init

and checking all the files in:

git add .
git commit -m”Initial commit.”

Heroku has what it calls a ‘Toolbelt’ which is a command line tool for creating and manipulating Heroku apps. Creating an app is very simple:

heroku create nakedlogs
Creating nakedlogs... done, stack is cedar-14
https://nakedlogs.herokuapp.com/ | https://git.heroku.com/nakedlogs.git
Git remote heroku added

Heroku needs to know how to start the new app and for that we need to supply a Procfile which is executed when the app is started:

web: node server.js

This is telling Heroku that it needs to start a web process and execute the server.js file using Node.js. The Procfile needs to be added to the repository and checked in too. Heroku likes to specify the port an app runs on, so the server.js file needs to be modified to read the port from the Heroku environment:

// start listening on Heroku port or port 8080
app.listen(process.env.PORT || 8080);

Once modified, the server.js file needs to be checked in. Then the repository needs to be pushed to Heroku:

git push heroku master
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (8/8), 1.25 KiB | 0 bytes/s, done.
Total 8 (delta 1), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Node.js app detected
remote: 
remote: -----> Creating runtime environment
remote:        
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NPM_CONFIG_PRODUCTION=true
remote:        NODE_ENV=production
remote:        NODE_MODULES_CACHE=true
remote: 
remote: -----> Installing binaries
remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:        
remote:        Resolving node version (latest stable) via semver.io...
remote:        Downloading and installing node 0.12.7...
remote:        Using default npm version: 2.11.3
remote: 
remote: -----> Restoring cache
remote:        Loading 1 from cacheDirectories (default):
remote:        - node_modules
remote: 
remote: -----> Building dependencies
remote:        Pruning any extraneous modules
remote:        Installing node modules (package.json)
remote: 
remote: -----> Caching build
remote:        Clearing previous node cache
remote:        Saving 1 cacheDirectories (default):
remote:        - node_modules
remote: 
remote: -----> Build succeeded!
remote:        └── express@4.13.3
remote:        
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote: 
remote: -----> Compressing... done, 9.9MB
remote: -----> Launching... done, v4
remote:        https://nakedlogs.herokuapp.com/ deployed to Heroku
remote: 
remote: Verifying deploy.... done.
To https://git.heroku.com/nakedlogs.git
 * [new branch]      master -> master

The app can then be accessed on Heroku via a web browser:

https://nakedlogs.herokuapp.com/

I’m reasonably pleased with myself. I was able to follow Richard’s instructions and build a simple web application with Node.js and Express and get it running on Heroku. I wonder what Richard will have for me to do next? In my application I would like to:

  • Use bootstrap and a templating library
  • Authenticate and administer users
  • Make RESTful web service calls



Comments

Popular posts from this blog

Write Your Own Load Balancer: A worked Example

I was out walking with a techie friend of mine I’d not seen for a while and he asked me if I’d written anything recently. I hadn’t, other than an article on data sharing a few months before and I realised I was missing it. Well, not the writing itself, but the end result. In the last few weeks, another friend of mine, John Cricket , has been setting weekly code challenges via linkedin and his new website, https://codingchallenges.fyi/ . They were all quite interesting, but one in particular on writing load balancers appealed, so I thought I’d kill two birds with one stone and write up a worked example. You’ll find my worked example below. The challenge itself is italics and voice is that of John Crickets. The Coding Challenge https://codingchallenges.fyi/challenges/challenge-load-balancer/ Write Your Own Load Balancer This challenge is to build your own application layer load balancer. A load balancer sits in front of a group of servers and routes client requests across all of the serv...

Catalina-Ant for Tomcat 7

I recently upgraded from Tomcat 6 to Tomcat 7 and all of my Ant deployment scripts stopped working. I eventually worked out why and made the necessary changes, but there doesn’t seem to be a complete description of how to use Catalina-Ant for Tomcat 7 on the web so I thought I'd write one. To start with, make sure Tomcat manager is configured for use by Catalina-Ant. Make sure that manager-script is included in the roles for one of the users in TOMCAT_HOME/conf/tomcat-users.xml . For example: <tomcat-users> <user name="admin" password="s3cr£t" roles="manager-gui, manager-script "/> </tomcat-users> Catalina-Ant for Tomcat 6 was encapsulated within a single JAR file. Catalina-Ant for Tomcat 7 requires four JAR files. One from TOMCAT_HOME/bin : tomcat-juli.jar and three from TOMCAT_HOME/lib: catalina-ant.jar tomcat-coyote.jar tomcat-util.jar There are at least three ways of making the JARs available to Ant: Copy the JARs into th...

RESTful Behaviour Guide

I’ve used a lot of existing Representational State Transfer (REST) APIs and have created several of my own. I see a lot of inconsistency, not just between REST APIs but often within a single REST API. I think most developers understand, at a high level, what a REST API is for and how it should work, but lack a detailed understanding. I think the first thing they forget to consider is that REST APIs allow you to identify and manipulate resources on the web. Here I want to look briefly at what a REST API is and offer some advice on how to structure one, how it should behave and what should be considered when building it. I know this isn’t emacs vs vi, but it can be quite contentious. So, as  Barbossa from Pirates of the Caribbean said, this “...is more what you’d call ‘guidelines’ than actual rules.” Resources & Identifiers In their book, Rest in Practice - Hypermedia and Systems Architecture (‎ISBN: 978-0596805821), Jim Webber, Savas Parastatidis and Ian Robinson describe resour...