Node.js

Junghoo Cho

cho@cs.ucla.edu

Node.js: Overview

Node.js: Single-Thread

Node.js Everywhere!

Node Interactive Shell Demo

$ node
> console.log("Hello world");
Hello world
undefined
> .help
.break    Sometimes you get stuck, this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the repl
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file    
> .exit

Executing JavaScript File

Code Example: Web Server (1)

// ---------- app.js ----------
let http = require("http");

// Create HTTP server and listen on port 3000 for requests
let httpServer = http.createServer((request, response) => {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.write("Hello World!\n");
    response.end("PATH: " + request.url);
})

httpServer.listen(3000);
console.log("I am here!");

Code Example: Web Server (2)

  1. require("http")
  2. http.createServer(callback)
  3. httpServer.listen(3000)

Module in Node.js

Node Module Example

//------ lib.js ------
function square(x) {
    return x ** 2;
}

function dist(x, y) {
    return Math.sqrt(square(x) + square(y));
}

module.exports = { square, dist };

//------ main.js ------
let lib = require('./lib');
console.log(lib.square(10));
console.log(lib.dist(4, 3));

Node Package Manager (NPM)

package.json File

Using package.json

$ npm init -y
$ npm install express

package.json Example

{
    "name": "application-name",
    "version": "0.0.0",
    "scripts": {
        "start": "node ./bin/www"
    },
    "dependencies": {
        "express": "4.9.0",
        "cookie-parser": "~1.3.3",
        "ejs": "^1.6.0"
    } 
}

Semantic Versioning (SemVer)

Global Package Installation

What We Learned