Book Image

Node.js Blueprints

By : Krasimir Stefanov Tsonev
Book Image

Node.js Blueprints

By: Krasimir Stefanov Tsonev

Overview of this book

Table of Contents (19 chapters)
Node.js Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Running the server


Before we start using Socket.IO, let's first write a simple Node.js server code, which responds with the chat's page. We can see the server code as follows:

var http = require('http'),
  fs = require('fs'),
  port = 3000,
  html = fs.readFileSync(__dirname + '/html/page.html', {encoding: 'utf8'}),
  css = fs.readFileSync(__dirname + '/css/styles.css', {encoding: 'utf8'});

var app = http.createServer(function (req, res) {
  if(req.url === '/styles.css') {
    res.writeHead(200, {'Content-Type': 'text/css'});
    res.end(css);
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
  }
}).listen(port, '127.0.0.1');

The preceding code should be placed in /index.js. The script starts with the definition of several global variables. The http module is used to create the server, and the fs module is used to read the CSS and HTML files from the disk. The html and css variables contain the actual code that will be sent to the browser. In our case, this...