Scaling Websites, Node.js




CS174

Chris Pollett

May 1, 2017

Outline

Benchmarking

Scaling a Web-site

Example Web-site Architecture

Organization of a website show squids, http servers, memcached server, databases.

Quiz

Which of the following statements is true?

  1. When the XmlHttpRequest object's readyState property is 4, the server's response to a sent request has been completely received.
  2. In REST, the remote procedure call is specified by sending the server an XML message with the name of an object and method.
  3. Target blank attacks, as described in class, can allow an attacker to hack a user's account without social engineering.

Database Part of the Architecture

ORMCache Part of the Architecture

Reverse Proxy Part of the Architecture

Content Delivery Networks

C10k Problem and its Variants

Node.js -- Introduction

Example Node application

var http = require('http'); // module pattern object for creating a server
   // If want ssl use require('https') and add key info

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'}); 
    // 1st arg is HTTP response type, 2arg is HTTP headers as JSON object
    response.end('Node is working\n');
    // body of response
}).listen(8888);

console.log("Server is up!");

Example Parsing the Query String

var http = require('http');
var fs = require('fs');

http.createServer(function (request, response) {
    var name = require('url').parse(request.url, true).query.name;
    // gets name from the query string
    if (name === undefined) {
        name = "myphoto";
    }
    if (name == 'myphoto') {
        var file_name = name + '.jpg';
        fs.stat(file_name, function (error, status) {
            //callback when promise ready. I.e., have stat info about file
            if (error) {
                console.error(error);
                response.writeHead(404, {'Content-Type': 'text/plain'});
                response.end("myphoto.jpg not available!");
            } else {
                var image = fs.readFileSync(file_name);
                response.contentType = 'image/jpeg'; 
                    //alternative was to set Content-Type
                response.contentLength = status.size;
                response.end(image, 'binary'); // send JPEG photo
            }
        });
    } else {
        response.writeHead(200, {'Content-Type': 'text/plain'}); 
        response.end('Name was:' + name);
    }
}).listen(8888);

console.log("Server is up!");

Node's Package Manager

Express.js

Express index.js file Example

var express = require('express')
var app = express()

// can add different routes
app.get('/', function (req, res) {
  res.send('This is an express app using route /')
})

app.listen(8888, function () {
  console.log('Server up!')
})

We can then run the project by typing at a shell prompt:

node index.js