Thursday, July 05, 2012

Simple application using ExpressJS, SocketIO & EJS

I came across EJS (JSP look-a-like for Node) and fell in love at first site, there are some other view rendering engines like Jade, but EJS clicked me as I saw it. So just went down to have a look my first app. There were some problems I faced regarding the API changes made in express latest version which I resolved with some googling. Lets get down to the code.

Create the test application with folder structure as below.

var express = require('express');
var io = require('');
var http = require('http');
var app = express();
var server = http.createServer(app);
var listener = io.listen(server);
  app.use(express.static(__dirname + '/views'));
  app.set('view engine', 'ejs');
  app.set('view options', {
    layout: false
app.get('/', function(req, res) {
  res.render('index', {
    title : 'Welcome to Express EJS',
    message : 'Below you will see the message recieved via event'
listener.on('connection', function (socket) {
  console.log('Connection to client established');
  socket.emit('news', 'This is the news');
  socket.on('newsresponse', function (data) {
    console.log('Server has disconnected');

<title><%= title %></title>
<script src="/"></script>
<script src="/jquery.min.js"></script>
var socket = io.connect('http://localhost:8080');
socket.on('connect',function() {
  console.log('Client has connected to the server!');
socket.on('news', function (data) {
  socket.emit('newsresponse', 'this is news response');
<p><%= message %></p>
<div style="color:#3333ff;" id='iomsg'></div>

If you come across any undefined modules, just do and "npm install <module>". Run the server "node server.js" and then try to access "http://localhost:8080"


  1. This comment has been removed by the author.


  2. Thank you very much for such a detailed and useful information!
    It is well demonstrated by the concept of code, thanks for sharing
    Richard Brown due diligence data room

  3. Well, it was useful and quite clear. Than you for adding those materials here. I hope that it will be useful for me and for the others too.

  4. Thanks for sharing this detailed and very useful instruction. I will definitely take advantage of this knowledge.

  5. Yes, i can agree with the previous reader, that was really useful. I hope that you'll add here more content like that. So we could use those skills too.