TABLE OF CONTENTS (HIDE)

Node.js

Basics

Introduction

JavaScripts typically run under a web browser (such as Chrome, Firefox). Node.js is a JavaScript engine that allows you to run JavaScript in standalone manner, without using a browser.

Node.js can also be used as a web server. This is popular because you can use the same JavaScript language to program the client as well as the server.

[TODO]

Installation

On Ubuntu
  1. Download Node.js from https://nodejs.org/. Choose Linux platform (e.g., node-v0.12.3-linux-x64.tar.gz).
  2. Unzip into a directory of your choice (e.g., /usr/local or /usr/local/lib).
  3. Node.js has two executables in its bin sub-directory: node (the standalone JavaScript engine) and npm (Node.js Package Manager). Instead of adding the bin directory to the PATH, you can create symlinks in one of the PATH directories. For example, I create symlinks in /usr/local/bin (which is in the PATH), as follows:
    $ cd /usr/local/bin
     
    // Create symlinks, may need to sudo
    $ ln -s /path-to-nodejs/bin/node
    $ ln -s /path-to-nodejs/bin/npm
     
    // Set to executable, may need to sudo
    $ chmod +x node
    $ chmod +x npm
  4. To test the Node engine, run node and enter JavaScript statements:
    $ node
    > console.log('hello');
    hello
    undefined
    > console.log(11 + 22);
    33
    undefined
    > .exit
Install Other node packages

You can install other node packages easily via npm (Node.js Package Manager). For example,

// Install Less, a CSS preprocessor. May need to sudo
$ npm install -g less
      // Installed under /usr/local/lib/node_modules/less
      // A symlink lessc created in /usr/local/bin
 
// Install Gulp, an automation tool. May need to sudo
$ npm install -g gulp
      // Installed under /usr/local/lib/node_modules/gulp
      // A symlink gulp created in /usr/local/bin

Node.js By Examples

Example 1: Node as a Web Server

Create the following JavaScript file, and save as "NodeExHttp.js" in a directory of your choice.

1
2
3
4
5
6
7
// NodeExHttp.js: Running Node as a web server
var http = require('http');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/html'});
  response.end('<h1>Hello World</h1>');
}).listen(9999, 'localhost');
console.log('HTTP Server running at http://localhost:9999/');

Run the NodeExHttp.js using Node.js (as a standalone program) as follows, which starts a HTTP server process.

$ cd /path-to-JavaScript
$ node NodeEx1.js
HTTP Server running at http://localhost:9999/

From a browser (Chrome, Firefox), issue URL http://localhost:9999/. You shall see the hello-world message.

To stop the server, press Ctrl-C (or Ctrl-Shift-C).

How It Works?
  1. [TODO]

REFERENCES & RESOURCES

  1. Node.js mother site @ https://nodejs.org/..