Node.js “in simple words” is server-side JavaScript. It has been getting a lot of buzz these days. If you’ve heard of it or you’re interested in learning and getting some hands on it – this post is for you.

Introduction

Node.js is an open source Javascript runtime environment for easily building server-side and networking applications. The platform runs on Linux, OS X, FreeBSD, and Windows.

Installation Overview

Installing Node and NPM is pretty straightforward using the installer package available from the Node.js® web site.

Installation Steps

  1. Download the Windows installer from the Nodes.js® web site.
  2. Run the installer (the .msi file you downloaded in the previous step.)
  3. Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).

Test it!

Make sure you have Node and NPM installed by running simple commands to see what version of each is installed and to run a simple test program:

  • Test Node. To see if Node is installed, open the Windows Command Prompt, Powershell or a similar command line tool, and type node -v.
  • Test NPM. To see if NPM is installed, type npm -v in Terminal. This should print NPM’s version number.

Setting up package.json

Assuming that you have already installed node, we must first create a package.json file. The npm utility can help you with that.

Go to your project folder and open up Terminal (or Command Prompt) and enter the following command:

npm init

Also you can use different tool to manage your packages by use Bower!

What the difference between bower and npm

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html,css,js etc. The fact that npm provides some packages which can be used in front-end development .

You’ll start by installing the Bower command-line utility and then go on to learn about the various commands that are available for managing packages.

Installing Bower

Bower can be installed using npm, the Node package manager.

go to your project folder and open up Terminal (or Command Prompt) and enter the following command: (This will install Bower globally on your system.)

npm install -g bower

Interactively create a bower.json with bower init

bower init

Installed packages will be placed in a bower_components directory. This is created in the folder which the bower program was executed. You can change this destination using the configuration options in a .bowerrc file.

Maintaining dependencies

Using bower install <package> --save will add <package> to your project’s bower.json dependencies array, install package and add it to bower.json dependencies

bower install <package> --save

Getting the Socket.IO Server

The officially maintained Socket.IO server is written in Node.JS and available on NPM

npm install socket.io

We distribute the browser client through our CDN, for free, forever.

<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>

A standalone build of socket.io-client is exposed automatically by the socket.io server as /socket.io/socket.io.js ,

If you want to grab the source, grab the socket.io.js file from the socket.io-client repository or install it .

npm install socket.io-client

A quick example of using node.js with socket.io

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

server = http.createServer(function(req, res){
    // your normal server code
    var path = url.parse(req.url).pathname;
    switch (path){
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write('<h1>Hello! Try the <a href="/test.html">Test page</a></h1>');
            res.end();
            break;
        case '/test.html':
            fs.readFile(__dirname + path, function(err, data){
                if (err){ 
                    return send404(res);
                }
                res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'});
                res.write(data, 'utf8');
                res.end();
            });
        break;
        default: send404(res);
    }
}),

send404 = function(res){
    res.writeHead(404);
    res.write('404');
    res.end();
};

server.listen(3000);

// use socket.io
var io = require('socket.io').listen(server);

//turn off debug
io.set('log level', 1);

// define interactions with client
io.sockets.on('connection', function(socket){
    //send data to client
    setInterval(function(){
        socket.emit('date', {'date': new Date()});
    }, 1000);

    //recieve client data
    socket.on('client_data', function(data){
        process.stdout.write(data.letter);
    });
});

 

<!doctype html>
<html>
  <head>
    <title>Socket.io Test</title>
    <script src="bower_components/socket.io-client/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  </head>
  <body>
    <script>    
      var socket = io.connect();
      
      socket.on('date', function(data){
        $('#date').text(data.date);
      });
      $(document).ready(function(){
        $('#text').keypress(function(e){
          socket.emit('client_data', {'letter': String.fromCharCode(e.charCode)});
        });
      });
    </script>
    <div id="date"></div>
    <textarea id="text"></textarea>
  </body>
</html>

After you have saved the files, you can execute it from your terminal like so:

node server.js

Then, load http://localhost:3000/ in a browser to see the output !

 

Categorized in:

Framework, Website Development,