Sunday, 20 September 2015

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



No comments:

Post a Comment