Friday, January 15, 2016

Node and Express on OS X

Introduction

Node.js (aka "node") allows us to develop server-side web applications using Javascript.

Long ago, Javascript was client side only.  Node has done much to change both the perception and usage of Javascript in the enterprise.  Node enables Javascript to talk to the Operating System, exposes APIs for the file system, network streams, and so on.  Node is enabled via the Chrome V8 Javascript engine.

Express is a node.js web application framework.  For Java Enterprise (JEE) users, think of express as fulfilling some of the roles of Maven - we'll cover this in the article below.


Installation

Installation on Ubuntu is covered extensively in the reference section below.

On the Mac, simply type
$ brew install node

After installing Node.js, we want to install the Express Application Generator.  Think of Maven archetypes, the project templating toolkit commonly used in enterprise Java applications. An archetype is defined as an original pattern or model from which all other things of the same kind are made. Both Maven and Express Generator provide a consistent means of generating projects and go a long way toward enforcing standards between projects and within teams.

Installation is simple:
$ npm install express-generator -g

I had to update my path manually:
export PATH=$PATH:/opt/homebrew-cask/Caskroom/eclipse-jee/4.5/Eclipse.app/Contents/MacOS:/Users/craigtrim/workspaces/public/bash:/usr/local/Cellar/tomcat/8.0.28/:/usr/local/Cellar/node/5.4.0/libexec/npm/lib:/usr/local/Cellar/node/5.4.0/libexec/npm/bin
The red highlighted text at the end of the PATH was added manually.


Usage


Navigate to any directory, and type:
$ express <project-name>
This will generate a basic web application structure.

The express tutorial for Ubuntu covers the internals of this structure in more detail.

Note that there is a package.json file in the generated structure. To continue the Maven analogy, this is similar to a POM.xml file. It contains a list of dependencies that are used by the web application. After creating a Maven POM cycle, a life-cycle command is invoked (such as, "mvn clean build").

In this case, we'll use:
$ npm install
to download and install the dependencies for our new Node web application.

To test the installation, type
$ npm start

And if the installation was successful, you should be able to browse to
http://localhost:3000
and see this:



Customization


Customize the app.js to route requests from
http://localhost:3000/api?q=here%20is%20my%20question
to a Javascript file that that will handle the request.

In this simple example, the handler will take the request (q=Question) and render JSON to the consumer.


App.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/api', api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
The red highlighted code was added.

This code tells the Node web server that requests made to the api path should be routed to the Api.js file.


api.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res) {

 var url = require('url');
 var url_parts = url.parse(req.url, true);
 var query = url_parts.query;
  
 res.setHeader('Content-Type', 'application/json');
 res.send(JSON.stringify({ question: query.q }));

});

module.exports = router;


If executed correctly, this should return:


Further customization would likely include more advanced handling of GET requests, interfacing with other applications to provide responses, and POSTing data from forms.


References

  1. Installing Node.js on Ubuntu
    1. Node.js (aka "node") is javascript on the server.  
    2. Node enables Javascript to talk to the Operating System, exposes APIs for the file system, network streams, and so on.  
    3. Node is enabled via the Chrome V8 Javascript engine.
  2. Installing Express.js on Ubuntu
    1. Express is a node.js web application framework.
  3. Homebrew 
    1. A convenient package manager for the Mac
    2. "Homebrew installs the stuff you need that Apple didn’t."
  4. Node, Express, Swig, and MongoDB - Getting Started With CRUD
    1. An excellent tutorial upon which this post was partially based.

1 comment:

  1. Hello..Wonderful blog with very useful information. Thanks for sharing this information with us.
    Node JS Online training
    Node JS training in Hyderabad

    ReplyDelete