Showing posts with label NodeJS. Show all posts
Showing posts with label NodeJS. Show all posts

Thursday, July 05, 2012

Fiddle with EJS filters

Lets play with EJS filters a bit. Lets pay greetings to the first user in the array of names with a message as "Welcome <firstname> <lastname>"

Lets take the names in an array of objects as below:

var names = [{first: 'John', last: 'Scott'},
             {first: 'Rob', last: 'Miller'}];

Now lets create a filter to create the message, in this filter the first selected object will be passes, which comes from the previous filter "first"

ejs.filters.greeting = function(user){
  return 'Welcome ' + user.first + ' ' + user.last + '';
};

The call to the filter is made in the index.ejs file as below, here insted of first you can can also use last filter

<%=: users | first | greeting %>

Lets see the whole program.

server.js
var express = require('express');
var io = require('socket.io');
var http = require('http');
var ejs = require('ejs');
 
var app = express();
var server = http.createServer(app);
 
var names = [{first: 'John', last: 'Scott'},
             {first: 'Rob', last: 'Miller'}];
 
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  app.use(express.static(__dirname + '/'));
  app.set('view engine', 'ejs');
  app.set('view options', {
    layout: false
  });
});
 
ejs.filters.greeting = function(user){
  return 'Welcome ' + user.first + ' ' + user.last + '';
};
 
app.get('/', function(req, res) {
  res.render('index', {
    title : 'Welcome to Express EJS',
    users: names
  });
});
 
server.listen(8080);

index.ejs
<html>
 
<head>
<title><%= title %></title>
</head>
 
<body>
<p><%=: users | last | greeting %></p>
</body>
 
</html>

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.

server.js
var express = require('express');
var io = require('socket.io');
var http = require('http');
 
var app = express();
var server = http.createServer(app);
var listener = io.listen(server);
 
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
  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 socket.io 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(data);
  });
 
  socket.on('disconnect',function(){
    console.log('Server has disconnected');
  });
 
});
 
server.listen(8080);

index.ejs
<html>
<head>
<title><%= title %></title>
<script src="/socket.io/socket.io.js"></script>
<script src="/jquery.min.js"></script>
 
<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) {
  $("#iomsg").html(data);
  socket.emit('newsresponse', 'this is news response');
});
</script>
 
</head>
 
<body>
<p><%= message %></p>
<div style="color:#3333ff;" id='iomsg'></div>
</body>
 
</html>

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"

Thursday, June 28, 2012

Mootools Class in NodeJS global context - Second Approach

In my last article here, I described how to load Mootools class in NodeJS global context. What if I do not want to make use of include to load the class, is there a way I can still do it with require. So, lets rewrite the program, and check how to do it

Application.js
(function(){
 
var Application = this.Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
})();

So, now the main file contains the code as below

Server.js
require('./mootools');
require('./Application');
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Hope this will solve !

Wednesday, June 27, 2012

Mootools Class in NodeJS global context

In continuation of my previous articles, here I came across a requirement to load Mootools Class in NodeJS global context. Let me try to explain, NodeJS module system is one-on-one with module-on-file, which creates a problem. For example lets say I have a Class Application as described in my other article, defined in Application.js

Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
exports.Application = Application;

And now I try to make use in my Server as below

server.js
require('mootools');
var _Application = require('./Application');
 
var app = new _Application.Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Not so good, you see _Application.Application() to create the object, this is fine if you want to have module to be in its own context, but what about if you don't ? Lets check how to load the Application class in global context so you could create the object in old fashion way var app = new Application();

To do so, you do not have to export the class as before, so the new code becomes as follows

Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});

Create one file Include.js with the following contents
 
Include.js
var fs = require('fs');
var vm = require('vm');
 
(function(){
 
var include = this.include = function(path) {
    var code = fs.readFileSync(path);
    vm.runInThisContext(code, path);
}.bind(this);
 
})();

And the server file with following contents

server.js
require('./mootools');
require('./Include');
include('./Application.js');
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

The Include.js file have a function include that does the job of loading the javascript file in global context. So you can access the class the good way.

Working with Mootools & NodeJS - Second Approach

In my last article here, I described how to make use of Mootools in a NodeJS applications. It included defining a class Application and then doing stuff with it. The class itself was defined in the same server.js file. This sometimes (very often for me) becomes a bottleneck as we start to work with one class per file approach. So, lets rewrite the program, create the file Application.js with following contents below
Application.js
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});

exports.Application = Application;

So, now the main file contains the code as below
Server.js
require('./mootools');
var _Application = require('./Application');

var app = new _Application.Application();
app.on("done", function() { console.log("App done"); });
app.compute();

Working with Node.js & Mootools

This article will simply explain how to make use of Mootools with ServerSide JavaScript. I am focusing on NodeJS and will try to explain how to do it. I have worked on Mootools on client side in the past, but recently got a chance to work on NodeJS project, so it is based on my current experience with this project. Ok so lets get started with a simple example of creating a class, instantiating it object and calling some functions, here it goes.

server.js
require('mootools');
var Application = new Class(
{
    Implements: [process.EventEmitter],
    initialize: function()
    {
        console.log("App initialize");
    },
    compute: function()
    {
        console.log("App compute");
        this.emit("done");
    }
});
 
var app = new Application();
app.on("done", function() { console.log("App done"); });
app.compute();

You must have Server Side mootools in the current working directory, downlodable from Mootools Site
Try running the code.

E:\mootools-node>node server.js
App initialize
App compute
App done