Express

Lecture 06 — Data Engineering — Spring 2015

January 29, 2015

Express

  • Express is a web application framework written in Javascript for use in Node.js
  • Its design was influenced by Sinata
  • Express makes it easy to define the endpoints of your web-based service.
  • It also has features (such as serving static files) that allow you to create a website.
  • Express is a minimal framework. It is designed to be augmented by node packages
    • that are then wired in as middleware.

Express By Example

Let's develop a web service in Express... step by step!

Create a directory

  • Create a directory called express_test on your computer.
  • cd into that directory
  • Invoke npm init

$ mkdir express_test
$ cd express_test
$ npm init
					

Answering the Questions (1)

Question Answer
Nametest_service
Version0.0.1
DescriptionMy express web service
Entry Pointtest.js

Answering the Questions (2)

Question Answer
Test Command<leave blank>
Git Repository<leave blank>
Keywords<leave blank>
Author<your name>
LicenseMIT

package.json

  • The output of the npm install command is a text file called package.json.
  • package.json is used by npm to keep track of the dependencies of this particular project (i.e. folder)
  • Each individual project has its own dependencies, unless you ask npm to make a particular module available globally.
  • If you download a project that contains a package.json file, you can run the command npm install to ask npm to download any required modules.

Installing Express

  • Let's install express:

npm install --save express

  • Take a look at your directory:
    • A new folder has been created: node_modules
    • npm updated your package.json file to contain the new dependency
  • If you had left out the --save flag, express would have been installed but your package.json file would have been left alone.

Installing Middleware

  • Let's also install two middleware packages
    • body-parser: for automatic parsing of HTTP request messages
    • morgan: for automatic logging of incoming requests


npm install --save body-parser
npm install --save morgan
					

npm list

  • Too see what npm installed, try typing:


npm list
					

  • You will see that npm installed the requested packages plus their dependencies.
  • All of the installed modules live in the node_modules directory.
  • If you want to see what modules are globally installed, include the --global flag in the command

Creating test.json

  • Let's start with a simple GET request

var express = require('express');
var parser  = require('body-parser');
var logger   = require('morgan');

var app = express();

app.set('port', process.env.PORT || 3000);
app.set('env', process.env.NODE_ENV || 'development')

app.use(logger('dev'));

app.get('/api/1.0/current_time', function(req, res) {
  res.json({ status: true, time: new Date()});
});
					

Try It!

node test.js
  • Nothing happened!
  • Why?

Node's Execution Model

  • Nothing happened because our code doesn't schedule any work yet
  • We declared a route but we forgot to start the server!
  • Add at the bottom of test.js:

app.listen(app.get('port'), function() {
  var message = 'Express started on http://localhost:';
  console.log(message + app.get('port'));
  message = 'Express is executing in the ';
  console.log(message + app.get('env') + ' environment.');
});
					

Try It (Again)!

node test.js
  • Server is running!

curl http://localhost:3000/api/1.0/current_time
{"status":true,"time":"2015-01-26T03:25:05.913Z"}
					

Boom!

  • Just like that, you have a simple web service!
  • That default time stamp was a bit underwhelming. Let's see if we can clean it up.
    • Rather than add any more code to our route, let's create our own module!

Creating a module

  • Install Moment.js
  • Create a directory called lib
  • cd into that directory
  • Create a file called time.js

npm install moment --save
mkdir lib
cd lib
vi time.js (or however you want to do it!)
					

Our Time Module

Edit time.js to look like this


var moment = require('moment');

var current_time = function() {
  var current = moment().format('LL; LTS');
}

exports.current_time = current_time;
					

Back in test.js

Import our module at the top


var time = require('./lib/time');
					

Change the body of our current_time route to:


res.json({ status: true, time: time.current_time()});
					

Try It!

node test.js
  • Access the endpoint:

curl http://localhost:3000/api/1.0/current_time
{"status":true,"time":"January 25, 2015; 9:09:16 PM"}
					

Adding a POST request

Let's add an endpoint that will calculate how far away a given date is from today.

In test.js, make the following changes:


// Add before the line app.use(logger('dev'))
app.use(parser.json());

// Add before the call to app.listen
app.post('/api/1.0/from_now', function(req, res) {
  res.json({ status: true, data: time.from_now(req.body.date)});
});
					

Modify time.js

In time.js, make the following changes:


// Add this function after the current_time function
var from_now = function(date) {
  return moment(date, 'YYYY-MM-DD').fromNow();
}

// Add at the end of the file
exports.from_now = from_now;
					

curl and POST request

To use the new endpoint, type:


# Type all on one line
curl -X POST --data '{"date":"2012-01-25"}'
--header "Content-Type: application/json"
http://localhost:3000/api/1.0/from_now

{"status":true,"data":"3 years ago"}
					

Your Turn!

  • Take a look at the docs for the Moment.js library
  • Identify a feature of Moment.js that you would like to expose via your web service.
  • Add the appropriate function to time.js
  • Add the appropriate route to test.js
  • Determine how to invoke curl to test your new endpoint.

GOOD LUCK!