Tag Archives: Socket.io

Getting started with Socket.io: Adding Real Time Events to your Node.js Express App


Getting started with Socket.io: Adding Real Time Events to your Node.js Express App
// Twilio Cloud Communications Blog

In a previous post, I explained how to monitor phone calls sent with the Twilio API in real time using call progress events. These allow you to set up a webhook url to receive a request whenever the status of your phone calls change.

The real time updates of call progress events provide us with a great opportunity to play around with websockets. In this post I am going to show you how to extend an already existing Express app to add real time communication between the client and server. We will be turning the Express server from my previous post into the backend of a dashboard for monitoring calls in real time using socket.io.

How to install Socket.io on NodeJS on Windows


How to install Socket.io on Node.js on Windows
// CodeProject Latest Articles

This article is about installing socket.io on node.js on windows 8.

Build a NodeJS Powered Chatroom Web App Part 3: Node, MongoDB and Socket


 Build a Node.js-powered Chatroom Web App: Node, MongoDB and Socket
// Kogonuso

sshot-10600.png
This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
This Node.js tutorial series will help you build a Node.js-powered real-time chatroom web app fully deployed in the cloud. In this series, you will learn how to setup Node.js on your Windows machine (or just learn the concepts if you’re on Mac), how to develop a web frontend with Express, how to deploy a Node.js Express app to Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together.
The tutorial will use the optional Visual Studio and the Node.js Tools for Visual Studio plug-in as a development environment. I have provided links to free downloads of both tools. This is a beginner to intermediate-level article –you’re expected to know HTML5 and JavaScript.

Part 1 – Introduction to Node.js
Part 2 – Welcome to Express with Node.js and Azure
Part 3 – Building a Backend with Node.js, Mongo and Socket.IO
Part 4 – Building a Chatroom UI with Bootstrap
Part 5 – Connecting the Chatroom with WebSockets
Part 6 – The Finale and Debugging Remote Node.js Apps

Part 3 – Building a Chatroom Backend with Node.js, Socket.IO and Mongo

Welcome to Part 3 of the hands-on Node.js tutorial series: Build a Node.js-powered chatroom web app. In this installment, I will show you how to use your existing express-based Node.js app to create a chatroom backend with WebSocket support.

What are WebSockets? What is Socket.IO?

WebSocket is a protocol designed to allow web applications to create a full-duplex channel over TCP (i.e. to have bi-directional communication) between the web browser and a web server. It is fully compatible with HTTP and uses TCP port number 80. WebSocket has allowed web applications to become real-time and support advanced interactions between the client and the server. It is supported by several browsers including Internet Explorer, Google Chrome, Firefox, Safari and Opera.
Socket.IO is a JavaScript library and Node.js module that allows you to create real-time bidirectional event-based communication apps simply and quickly. It simplifies the process of using WebSockets significantly. We will be using Socket.IO v1.0 to make our chatroom app.

Adding Socket.IO to package.json

package.json is a file that holds various metadata relevant to the project, including its dependencies. npm can use this file to download modules required by the project. Take a look at this interactive explanation of package.json and what it can contain.
Let’s add Socket.IO to the project as a dependency. There are two ways to do that.

  1. If you have been following the tutorial series and have a project in Visual Studio setup, right-click on the npm part of the project and select “Install New npm Packages…”

1428380897image_0.jpg
Once the window has opened, search for “socket.io”, select the top result and check the “Add to package.json” checkbox. Click the “Install Package” button. This will install Socket.IO into your project and add it to the package.json file.
1428380891image_1.jpg
package.json

{
"name": "NodeChatroom",
"version": "0.0.0",
"description": "NodeChatroom",
"main": "app.js",
"author": {
"name": "Rami Sayar",
"email": ""
},
"dependencies": {
"express": "3.4.4",
"jade": "*",
"socket.io": "^1.0.6",
"stylus": "*"
}
}
  1. If you’re on OS X or Linux, you can achieve the same action as the above by running the following command in the root of your project folder.
npm install --save socket.io

Adding Socket.IO to app.js

The next step is to add Socket.IO to app.js. You can achieve this by replacing the following code…

http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

…with:

var serve = http.createServer(app);
var io = require('socket.io')(serve);
serve.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});

This will capture the HTTP server in a variable called serve and pass that HTTP server so that the Socket.IO module can attach to it. The last code block takes the serve variable and executes the listen function which starts the HTTP server.

Logging a User Joining and Leaving

Ideally, we want to log a user joining the chatroom. The following code accomplishes that by hooking a callback function to be executed on every single connection event via WebSocket to our HTTP server. In the callback function, we call console.log to log that a user connected. We can add this code after we call serve.listen.

io.on('connection', function (socket) {
console.log('a user connected');
});

To do the same for when a user disconnects, we have to hook up the disconnect event for each socket. Add the following code inside after the console log of the previous code block.

socket.on('disconnect', function () {
console.log('user disconnected');
});

Finally, the code will look like this:

io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});

Broadcasting a Message Received on the Chat Channel

Socket.IO gives us a function called emit to send events.
Any message received on the chat channel will be broadcast to all the other connections on this socket by calling emit with the broadcast flag in the callback.

socket.on('chat', function (msg) {
socket.broadcast.emit('chat', msg);
});

Finally, the code will look like this:

io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('chat', function (msg) {
socket.broadcast.emit('chat', msg);
});
});

Saving Messages to a NoSQL Database

The chatroom should save chat messages to a simple data store. Normally, there are two ways to save to a database in Node; you can use a database-specific driver or you can use an ORM. In this tutorial, I will show you how to save the messages to MongoDB. Of course, you can use any other database you like, including SQL databases like PostgreSQL or MySQL.
You should make sure you have a MongoDB to connect to. You can use a third-party service to host your MongoDB such as MongoHQ or MongoLab. Take a look at this tutorial to see how you can create a MongoDB using the MongoLab Add-On in Azure. You can stop reading when you get to the section “Create the App”, just make sure to save the MONGOLAB_URI somewhere you can access easily later.
Once you have created a MongoDB and you have the MONGOLAB_URI for the database – Under Connection info that you have copied to your clipboard – you will want to ensure that the URI is available to the application. It is not best practice to add sensitive information such as this URI into your code or into a configuration file in your source code management tool. You can add the value to the Connection Strings list in the Configuration menu of your Azure Web application (such as in the tutorial you used) or you can add it to the App Setting list (with Name CUSTOMCONNSTR_MONGOLAB_URI). On your local machine, you can add it to the environment variables with the name CUSTOMCONNSTR_MONGOLAB_URI and value of the URI.
The next step is to add support for MongoDB to our project. You can do that by adding the following line to the dependencies object in package.json. Make sure to save your changes to the file.

"mongodb": "^1.4.10",

Right-click on the npm part of the project in the Solution Explorer to reveal the right-click context menu. Click “Install missing packages” from the content menu to install the MongoDB package so that it can be used as a module.
1428380887image_2.png
We want to import that module to be able to use the MongoDB client object in app.js. You can add the following lines of code after the first require('') function calls, such as on line 11.

var mongo = require('mongodb').MongoClient;

We want to connect to the database using the URI we have in the CUSTOMCONNSTR_MONGOLAB_URI environment variable. Once connected, we want to insert the chat message received in the socket connection.

mongo.connect(process.env.CUSTOMCONNSTR_MONGOLAB_URI, function (err, db) {
var collection = db.collection('chat messages');
collection.insert({ content: msg }, function(err, o) {
if (err) { console.warn(err.message); }
else { console.log("chat message inserted into db: " + msg); }
});
});

As you can see in the above code, we use the process.env object to get the environment variable value. We go into a collection in the database and we call the insert function with the content in an object.
Every message is now being saved into our MongoDB database.

Emitting the Last 10 Messages Received

Of course, we don’t want our users to feel lost once joining the chatroom, so we should make sure to send the last 10 messages received to the server so at the very least we can give them some context. To do that, we need to connect MongoDB. In this case, I am refraining from wrapping all of the socket code with one connection to the database so that I can still have the server working even if it loses the database connection.
We will also want to sort and limit my query to the last 10 messages, we will use the MongoDB generated _id as it contains a timestamp (although in more scalable situations, you will want to create a dedicated timestamp in the chat message) and we will call the limit function to limit the results to only 10 messages.
We will stream the results from MongoDB so that I can emit them as soon as possible to the chatroom as they arrive.

mongo.connect(process.env.CUSTOMCONNSTR_MONGOLAB_URI, function (err, db) {
var collection = db.collection('chat messages')
var stream = collection.find().sort({ _id : -1 }).limit(10).stream();
stream.on('data', function (chat) { socket.emit('chat', chat.content); });
});

The above code does the job as explained in the previous paragraphs.

Deploying to Azure

You can redeploy to Azure by following the past tutorials (such as part 2).

Conclusion

In conclusion, we have a chat system capable of broadcasting a message received via WebSockets to all other connected clients. The system saves the message to the database and retrieves the last 10 messages to give context to every new user who joins the chatroom.

Stay Tuned for Part 4!

Part 4 — Building a Chatroom UI with Bootstrap is here. You can stay up-to-date on this and other articles by following my twitter account.

More Learning for Node on Azure

For more in-depth learning on node, my course is available here on Microsoft Virtual Academy.
Or some shorter-format videos on similar node subjects:

This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.

Rami Sayar is a technical evangelist at Microsoft Canada focusing on web development (JavaScript, AngularJS, Node.js, HTML5, CSS3, D3.js, Backbone.js, Babylon.js), open data and open source technologies (Python, PHP, Java, Android, Linux, etc.) Read his blog or follow him on Twitter.

—-

Shared via my feedly reader

Build a NodeJS powered Chatroom Web App Part 6: Debugging Remotely


Build a Node.js-powered Chatroom Web App: Debugging Remotely
// Kogonuso

sshot-10593.png
This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
This Node.js tutorial series will help you build a Node.js-powered real-time chatroom web app fully deployed in the cloud. In this series, you will learn how to setup Node.js on your Windows machine (or just learn the concepts if you’re on Mac), how to develop a web frontend with Express, how to deploy a Node.js Express app to Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together.
The tutorial will use the optional Visual Studio and the Node.js Tools for Visual Studio plug-in as a development environment. I have provided links to free downloads of both tools. This is a beginner to intermediate-level article—you’re expected to know HTML5 and JavaScript.

Part 1 – Introduction to Node.js
Part 2 – Welcome to Express with Node.js and Azure
Part 3 – Building a Backend with Node.js, Mongo and Socket.IO
Part 4 – Building a Chatroom UI with Bootstrap
Part 5 – Connecting the Chatroom with WebSockets
Part 6 – The Finale and Debugging Remote Node.js Apps

Part 6 – The Finale and Debugging Remote Node Apps

Welcome to Part 6 of the hands-on Node.js tutorial series: Build a Node.js-powered chatroom web app.
In this final installment, I will show you how to do a final deployment of your chatroom and how to perform remote debugging.

Deploying to Azure

Now that we’ve got our Node.js-powered anonymous chatroom app working, let’s deploy it to the cloud in a few clicks. You can deploy to any cloud that supports Node.js. I will be using Microsoft Azure as I can run a Node.js website on there for free.
You can sign up for a free trial of Microsoft Azure here. You will get trial credits to spend on all Azure services. For the service we are using, Azure Websites, you can actually run 10 websites without spending a dime.

  1. Once you have your Azure account set up, go back to the IDE, right click on the project and click Publish.
    1428560674NodeJS-Article-6-01-06-Publishing-Via-Azure.png
  2. Clicking Publish will open a wizard with a few options, select the target Microsoft Azure Websites.
  3. You will be asked to sign in at this step, please use the same Microsoft Account here as you did on the Azure sign up.
  4. Click New to create a new Azure website or, if you already have one created, you can select it from the dropdown.
    1428560708NodeJS-Article-6-02-Publishing-New-Azure-Website.jpg
  5. You will want to complete the fields in the wizard (just like below). Make sure to choose a unique site name, and then click Create.
    1428560703NodeJS-Article-6-03-Completing-the-Wizard.png
  6. You will be presented with a pre-filled wizard. Click Publish.
    1428560697NodeJS-Article-6-04-Publishing-Final-Step.png

We’ve deployed to the cloud but the work is not over yet!

Enabling WebSockets in Azure Websites

There are a few things you need to do to ensure that WebSockets are enabled for your website. If you want more detailed steps or FAQ, be sure to visit this page.
First, you will need to enable WebSockets from the Azure command-line or the Configuration tab, like so:
1428560692NodeJS-Article-6-05-Enabling-Web-Sockets.png
Second, you will want to modify your web.config file and the following line to the system.webServer XML element.

<webSocket enabled="false" />

It may seem counterintuitive, but this disables the IIS WebSockets module, which includes its own implementation of WebSockets and conflicts with Node.js specific WebSockets modules such as Socket.IO.

Debugging Remote Node.js Apps

Node Tools for Visual Studio comes with several advanced debugging features such as conditional breakpoints, “hit count” breakpoints, tracepoints and remote debugging support for Windows, Linux and OS X. Read more here.

Connecting to Remote Node.js Instances

NTVS has support for remote debugging code running on Azure Web Sites. Unlike regular remote debugging, the target machine is not directly accessible over TCP. NTVS comes with a WebSocket proxy for the debugging protocol that exposes the debugger protocol via HTTP. When you create a new Windows Azure project, the proxy is fully configured for you in Web.Debug.config, and will be enabled on the Azure WebSite if you publish your project in the Debug configuration by following the next couple of steps.

  1. Right click on the project and select Publish.
    1428560674NodeJS-Article-6-01-06-Publishing-Via-Azure.png
  2. Select the Settings tab on the left and be sure to choose the Debug configuration from the dropdown.
    1428560687NodeJS-Article-6-07-Publishing-to-the-Web-in-Debug-Mode.jpg
  3. Click Publish.

Once your project is properly deployed and WebSockets are enabled, you can attach to the web site from Server Explorer. If you do not have the Server Explorer window open, you can open it via View → Server Explorer. Then, locate your web site under Windows Azure → Web Sites, and right-click on it. If it is running, and your project has been deployed to it using the Debug configuration, you should see the Attach Debugger (Node.js) command in the context menu.
1428560683NodeJS-Article-6-08-Attach-Node.js-Debugger.png

Reading Logs and Streaming Logs

If you want to stream the latest logs, it’s quite easy! All you have to do is right click on your website in the Server Explorer and choose View Stream Logs.
1428560678NodeJS-Article-6-09-Streaming-Logs.png

Conclusion

Voila! There you have it! You now have an anonymous, real-time chatroom in the cloud! Throughout this series, we learned how to set up Node.js, develop a web front-end with Express, deploy our app to the cloud, how to use Socket.IO to add a real-time layer, and then how to deploy it all together!
1428562937barney.gif
Be sure to reread the different parts on my blog as I may occasionally add updates to this tutorial. You can stay up-to-date on this and other articles by following my Twitter account
P.S. If you want more success GIFs, go here.

More learning for Node.js on Azure

For more in-depth learning on node, my course is available here on Microsoft Virtual Academy.
Or some shorter-format videos on similar node subjects:

This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.

Rami Sayar is a technical evangelist at Microsoft Canada focusing on web development (JavaScript, AngularJS, Node.js, HTML5, CSS3, D3.js, Backbone.js, Babylon.js), open data and open source technologies (Python, PHP, Java, Android, Linux, etc.) Read his blog or follow him on Twitter.

Build a NodeJS powered Chatroom Web App Part 4: Chatroom UI with Bootstrap


Build a Node.js-powered Chatroom Web App: Chatroom UI with Bootstrap
// Kogonuso

sshot-10599.png
This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
This Node.js tutorial series will help you build a Node.js-powered real-time chatroom web app fully deployed in the cloud. In this series, you will learn how to setup Node.js on your Windows machine (or just learn the concepts if you’re on Mac), how to develop a web frontend with Express, how to deploy a Node.js Express app to Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together.
The tutorial will use the optional Visual Studio and the Node.js Tools for Visual Studio plug-in as a development environment. I have provided links to free downloads of both tools. This is a beginner to intermediate-level article—you’re expected to know HTML5 and JavaScript.

Part 1 – Introduction to Node.js
Part 2 – Welcome to Express with Node.js and Azure
Part 3 – Building a Backend with Node.js, Mongo and Socket.IO

Part 5 – Connecting the Chatroom with WebSockets
Part 6 – The Finale and Debugging Remote Node.js Apps

Part 4 – Building a Chatroom UI with Bootstrap

Welcome to Part 4 of the hands-on Node.js tutorial series: Build a Node.js-powered chatroom web app.
In this installment, I will show you how to add a Twitter Bootstrap-styled frontend to the chatroom backend you built in Part 2 and Part 3.

What is Bootstrap?

Bootstrap is a wildly popular HTML and CSS framework for building websites and web applications. It is the number one project on GitHub. Bootstrap supports responsive web design, allowing the layout of your page to adapt to the device (desktop, tablet, mobile).

Adding Bootstrap to Our Project

To add Bootstrap to our project, we have to download the minified CSS and JS files for Bootstrap. You can download Bootstrap from this link. After you have downloaded Bootstrap, unzip the file and copy over the folders css, js, and fonts to the public folder in your project.
You will notice a few inconsistencies with the existing folder structure. We will unify the stylesheets and JavaScript folders. I prefer the Bootstrap nomenclature of css for stylesheets and js for javascript as that is shared with other third-party libraries. Copy the files in stylesheets into css and delete the javascript folder as it should be empty. Next go to layout.jade and change the following line:

link(rel='stylesheet' href='/stylesheets/style.css')

to:

link(rel='stylesheet' href='/css/style.css')

Next, we want to add the Bootstrap CSS file links to the header and the appropriate meta tags for HTML5 apps in the layout.jade file. You have to add the following lines right before the line containing the style.css link.

meta(charset="utf-8")
meta(http-equiv="X-UA-Compatible" content="IE=edge")
link(rel='stylesheet' href='/css/bootstrap.min.css')
link(rel='stylesheet' href='/css/bootstrap-theme.min.css')

Next, we want to add the JavaScript file that Bootstrap needs for its components and plugins. Add the following line to the end of layout.jade:

script(type=’text/javascript’ src=’/js/bootstrap.min.js’)

Completed layout.jade

doctype html
html
head
title= title
meta(charset="utf-8")
meta(http-equiv="X-UA-Compatible" content="IE=edge")
link(rel='stylesheet' href='/css/bootstrap.min.css')
link(rel='stylesheet' href='/css/bootstrap-theme.min.css')
link(rel='stylesheet' href='/css/style.css')
body
block content
script(type='text/javascript' src='/js/bootstrap.min.js')

Creating the Chat UI Layout

It is time to develop the chat user interface layout. First, you might want to read about Bootstrap and take a look at this long tutorial. All chat engines have an area for the recently received messages and an area for a user to write and send a message. Historically, the layout was to have the editing area attached to the bottom and the messages at the top.
It is not easy to fix elements on an HTML page to the bottom of the viewport without a bit of work. I will be following this sample to fix a footer to the bottom. We want to modify the index.jade file, and remove all the lines of code under the content block.
First, we add the area of the page that will contain messages received. Let’s start by adding a div with the class wrap. In Jade, all you need to write is .wrap to generate a

. By using the indentation, we can signal to the Jade templating engine that more indented elements will go within the less indented elements. Take a look at this Jade tutorial if you missed it in the other tutorials.
Next, we want to add another div with the class container-fluid to add a fluid width to the page. Inside, I will create an h1 element that says “Welcome to the Node Chatroom” and a div with an id messages and a final div with the class push that we will use to push down the message editing area of the chatroom to the bottom of the viewport.

.wrap
.container-fluid
h1 Welcome to the Node Chatroom
#messages
.push

Next, we are going to develop the message editing area. We want to capture the textbox and send button within a div called footer and a div called container-fluid. The footer div will have the same indentation as the wrap div.
Next, I will use the Bootstrap grid system (read about it here) to split the message editing area into two. One of the columns will take the majority of the space and will contain the textbox for writing the message, the second column will contain a block-level button for sending the message. Note how Jade lets us specify the attributes of an element using the paragraph notation. The code will look like this:

.footer
.container-fluid
.row
.col-xs-8.col-sm-9
input(type="text" id="message-box" class="form-control input-lg" placeholder="Write a message here..." rows="3")
.col-xs-4.col-sm-3
button#send-message-btn.btn.btn-primary.btn-lg.btn-block Send Message

Completed index.jade

extends layout
block content
.wrap
.container-fluid
h1 Welcome to the Node Chatroom
#messages
.push
.footer
.container-fluid
.row
.col-xs-8.col-sm-9
input(type="text" id="message-box" class="form-control input-lg" placeholder="Write a message here..." rows="3")
.col-xs-4.col-sm-3
button#send-message-btn.btn.btn-primary.btn-lg.btn-block Send Message

Adding CSS to Force the Message Editing Area to the Bottom of Viewport

We want to force the message editing area to the bottom of the viewport, we will want to add a few custom CSS rules in the public/css/style.styl page. This file uses the Stylus CSS preprocessor but you can also paste verbatim CSS that will be recopied into the generated CSS file.
First, we will want to ensure the whole page takes up 100% of the height.

html, body
height: 100%

Second, we want to ensure the wrap area takes up the maximum height it can but leaves a 60px margin at the bottom for our footer and message editing area.

.wrap
min-height: 100%
height: auto !important
height: 100%
margin: 0 auto -60px

Third, we want to ensure that this space for the editing area is respected and to assign it to the footer.

.push, .footer
height: 60px

Finally, for stylistic reasons, let’s add a subtle background color to the footer.

.footer
background-color: **#f5f5f5**

Completed style.styl

html, body
height: 100%
.wrap
min-height: 100%
height: auto !important
height: 100%
margin: 0 auto -60px
.push, .footer
height: 60px
.footer
background-color: #f5f5f5

Screenshot

If you did everything correctly, you should end up with a UI that looks like this:
1428455963Final-Screenshot-for-Node-UI.png

Conclusion

Voila! We have used Bootstrap and the Jade/Stylus preprocessors to add a nice UI layout for our chatroom that is served by Node.js. In the next installment, I will show you how to connect the UI and the Node.js backend via WebSockets.

Stay Tuned for Part 5!

Part 5 — Connecting the Chatroom with WebSockets is here. You can stay up-to-date on this and other articles by following my Twitter account

More Node.js Learning on Azure

For more in-depth learning on Node.js, my course is available here on Microsoft Virtual Academy.
Or some shorter-format videos on similar Node.js subjects:

This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.

Rami Sayar is a technical evangelist at Microsoft Canada focusing on web development (JavaScript, AngularJS, Node.js, HTML5, CSS3, D3.js, Backbone.js, Babylon.js), open data and open source technologies (Python, PHP, Java, Android, Linux, etc.) Read his blog or follow him on Twitter.

Build a NodeJS powered Chatroom Web App Part 1: Getting Started


Build a Node.js-powered Chatroom Web App: Getting Started
// Kogonuso

sshot-10596.png
This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
This Node.js tutorial series will help you build a Node.js-powered real-time chatroom web app fully deployed in the cloud. In this series, you will learn how to setup Node.js on your Windows machine (or just learn the concepts if you’re on Mac), how to develop a web frontend with Express, how to deploy a node express apps to Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together.
The tutorial will use the optional Visual Studio and the Node.js Tools for Visual Studio plug-in as a development environment—I have provided links to free downloads of both tools. This is a beginner- to intermediate-level article –you’re expected to know HTML5 and JavaScript.

Part 1 – Introduction to Node.js
Part 2 – Welcome to Express with Node.js and Azure
Part 3 – Building a Backend with Node.js, Mongo and Socket.IO
Part 4 – Building a Chatroom UI with Bootstrap
Part 5 – Connecting the Chatroom with WebSockets
Part 6 – The Finale and Debugging Remote Node.js Apps

Welcome to Part 1 of the hands-on Node.js tutorial series. In this instalment, I will explain what Node.js is, why you should pay attention to Node.js, and how to set up your machine.

What is Node.js? Why Use It?

Node.js is a runtime environment and library for running JavaScript applications outside the browser. Node.js is mostly used to run real-time server applications and shines through its performance using non-blocking I/O and asynchronous events. A complete web ecosystem has been built around Node.js with several web app frameworks and protocol implementations available for usage. It’s definitely one of the easiest and fastest way to develop real-time applications on the web today.
Why use Node.js? One word: JavaScript. JavaScript is an extremely popular language and is credited with being one of the driving forces that turned the web into the dynamic wonderland that it is today.
JavaScript arose on the front end but — thanks to the V8 JavaScript engine and the work of Ryan Dahl — you can now run networked JavaScript applications outside of the browser precisely to build web apps. Node.js lets you unify the programming language used by your app. No longer do you need a different language for your backend—you can use JavaScript throughout. If your background is in building and design websites and web app frontends in HTML, CSS and JavaScript, you don’t need to pick up another language to develop complex data-driven back-ends for your apps.
Node.js plays a critical role in the advancement of WebSockets as a method for real-time communication between the front and back ends. The use of WebSockets and the libraries building on that protocol such as Socket.IO have really pushed what is expected of web applications and lets us developers explore new ways to create the web.

How to Set Up Node.js on Windows 8

To get started, you’ll need a reasonably up-to-date machine. I will be showing you how to install Node.js on Windows 8.1.

1. Install Node.js

First, download and install the Node.js runtime. Choosing the Windows Installer is one of the easiest ways to get started.
Alternatively, if you are a fan of Chocolatey, the package manager for Windows, you can install Node.js by running:

choco install nodejs.install

2. Confirm set-up

You should double-check that the Node.js executable has been added to your PATH system environment variable. Watch this video if you want to see how to change your environment variables on Windows 8 and Windows 8.1. You will want to make sure the following folder has been added to the PATH variable:

C:\Program Files (x86)\nodejs\

If you go to your Command Prompt and type in node –h, you should see the help documentation for the node.js executable displayed.
Along with Node.js, npm, the system used to manage node.js packages, should be installed and available on the Command Prompt as well. Simply type in npm –h, you should see the help documentation for npm displayed.

In case of an error…

If you encounter an error similar to this one…

Error: ENOENT, stat 'C:\Users\someuser\AppData\Roaming\npm'

…the resolution is to create a folder at the path specified above, as shown in this StackOverflow question. This is only an issue in the latest Node.js installer and should be resolved by next release. You can create the folder like so:

mkdir -r C:\Users\someuser\AppData\Roaming\npm

Select a Development Tool

With Node.js installed, it’s time to select a development tool. Feel free to use any editing tool you want. Throughout these tutorials, I will use Visual Studio to develop, debug, and deploy the chat engine; as well as Node.js Tools for Visual Studio (NTVS) –a free open-source plug-in for Visual Studio that supports developing Node.js applications.
What’s cool about NTVS is that it adds Node.js support for editing, Intellisense, performance profiling, npm, TypeScript, debugging locally and remotely (including on Windows/MacOS/Linux). It also makes it easy to quickly create web sites and deploy them to Microsoft Azure Web Sites or Cloud Services.
If you do not have Visual Studio, you can download a free copy of Visual Studio 2013 Community Edition. Then, download the free Node.js Tools for Visual Studio plug-in. You may also use Visual Studio 2012 Pro or higher (requires Update 4) or Visual Studio 2013 or higher (requires Update 2). The NTVS plug-in is compatible with both editions.

Start a new Node.js project in Visual Studio

Note: Screenshots show Visual Studio 2013 Ultimate.
Starting a new Node.js project is fairly straightforward.

  1. Start Visual Studio. On the File menu, click New, and then click Project.
  2. In the New Project window, expand the Installed menu selection, expand Templates, and click JavaScript. In the main window, select Blank Node.js Web Application. Choose a location and name for your project, and then click OK.
  3. You will be presented with the following screen. Feel free to explore Visual Studio at this point. You will want to open the generated server.js file in the Solution Explorer (on the right typically but may be located elsewhere on your screen.)
  4. You can now debug your node.js web application in your preferred browser.

1427694211image06.png

A “Hello World” app in Node.js

Here’s the code used in the server.js file linked above.

var http = require('http');
var port = process.env.port || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(port);

As is typical in other languages, the generated code example shows you how to output “Hello World” in the browser. Let me explain how the generated code in server.js works line by line. As stated in this tutorial series description, I am assuming you have a knowledge of JavaScript, HTML5 and how HTTP/the Internet works.

Line 1

var http = require(‘http’);

Node.js has a simple module and dependencies loading system. You simply call the function “require” with the path of the file or directory containing the module you would like to load at which point a variable is returned containing all the exported functions of that module.

Line 2

var port = process.env.port || 1337;

On this line, we want to determine on which port the HTTP server serving the HTML should run. If a port number is specified in the environment variables, we will use that one or we will simply use 1337.

Line 3

http.createServer(function (req, res) {

We want to create a server to handle HTTP requests. We will also pass the createServer function a function callback containing two parameters to a handle each individual request and return a response. Take a look at Michael Vollmer’s article if you’ve never encountered callback functions in JavaScript. The request received is passed in the req parameter and the response is expected to written to the res parameter.

Line 4

res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });

Any HTTP response requires a status-line and headers, to learn more about HTTP headers and how they work check out this article. In this case, we want to return 200 OK as the status response and to specify the content-type as plain text. We specify this by calling the writeHead function on the response object.

Line 5

res.end(‘Hello World\n’);

Once we are done writing the response we want to call the end function. We can also pass the final content through the end function, in this case we want to send the string “Hello World” in plain text.

Line 6

}).listen(port);

We close off the callback and call the function listen at the port we defined earlier, this will start the server and start accepting requests sent to the defined port.
To see the result, you can start debugging by pressing on the button shown in the previous screenshot. You can see “Hello World” in the browser.
1427694207image05.png
Voila! You have now successfully run a Node.js app on Windows 8.1 using Visual Studio 2013.

Stay Tuned for Part 2!

Part 2—How to Deploy Your “Hello World” into the Cloud is here. You can stay up-to-date on this and other articles by following my twitter account.

More learning for Node on Azure

For more in-depth learning on node, my course is available here on Microsoft Virtual Academy.
Or some shorter-format videos on similar node subjects:

This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.

Rami Sayar is a technical evangelist at Microsoft Canada focusing on web development (JavaScript, AngularJS, Node.js, HTML5, CSS3, D3.js, Backbone.js, Babylon.js), open data and open source technologies (Python, PHP, Java, Android, Linux, etc.) Read his blog or follow him on Twitter.

Build a NodeJS powered Chatroom Web App Part 5: Connecting with WebSockets


Build a Node.js-powered Chatroom Web App: Connecting with WebSockets
// Kogonuso

sshot-10601.png
This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.This Node.js tutorial series will help you build a Node.js-powered real-time chatroom web app fully deployed in the cloud. In this series, you will learn how to setup Node.js on your Windows machine (or just learn the concepts if you’re on Mac), how to develop a web frontend with Express, how to deploy a Node.js Express app to Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together.
The tutorial will use the optional Visual Studio and the Node.js Tools for Visual Studio plug-in as a development environment. I have provided links to free downloads of both tools. This is a beginner to intermediate-level article –you’re expected to know HTML5 and JavaScript.

Part 1 – Introduction to Node.js
Part 2 – Welcome to Express with Node.js and Azure
Part 3 – Building a Backend with Node.js, Mongo and Socket.IO
Part 4 – Building a Chatroom UI with Bootstrap
Part 5 – Connecting the Chatroom with WebSockets
Part 6 – The Finale and Debugging Remote Node.js Apps

Part 5 – Connecting the Chatroom with WebSockets

Welcome to Part 5 of the hands-on Node.js tutorial series: Build a Node.js-powered chatroom web app.
In this installment, I will show you how to connect the front-end chatroom to the Node.js chatroom backend that you built in Part 2, Part 3 and Part 4.

Adding jQuery, SocketIO and index.js

The first thing we want to do before we start writing our front-end JavaScript code is to ensure the files and dependencies we need are going to be delivered by the Node.js server. Let’s add jQuery and Socket.IO first to the layout.jade file which is extended by all the other jade files in our project.
Replace the single link to bootstrap.min.js with a link to all the other files we need.

script(type='text/javascript'
src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery­2.1.1.min.js')
script(type='text/javascript' src='/js/bootstrap.min.js')
script(type='text/javascript' src='/socket.io/socket.io.js')

Note, the first line links to jQuery hosted on the Microsoft Ajax Content Delivery Network. This CDN hosts popular third party JavaScript libraries such as jQuery and enables you to easily add them to your Web applications. You can significantly improve the performance of your Ajax applications by using a CDN. The contents of the CDN are cached on servers located around the world. The CDN supports SSL (HTTPS) in case you need to serve a web page using the Secure Sockets Layer.
Now I will add one more line at the end to create a new block.

block body_end

I am doing this so that any Jade file that extends layout.jade can also add script tags right before the end of the body tag.
Now we want to use that new block to add a link to our index.js file which we will create in the public/js folder, make sure to create the file.

block body_end
script(type='text/javascript' src='/js/index.js')

Make sure that the block starts with zero indentation to follow Jade coding conventions. If you run the Node.js server and navigate to the main page in your browser, you will notice in your F12 tools that the files are being served correctly.

Quick Changes to app.js

There’s a few things I want to change in app.js. First, I want to reverse the sorting direction so that the oldest messages are sent first and second. I also want to emit the previously received chat messages on the same channel as I plan on receiving the new messages. The changes will go to line 49 and 50 in app.js. This is the result:

var stream = collection.find().sort().limit(10).stream();
stream.on('data', function (chat) { socket.emit('chat', chat.content); });

Don’t forget to set the CUSTOMCONNSTR_MONGOLAB_URI environment variable before rerunning the app.js file as otherwise the Node.js backend will crash when it can’t connect to your MongoDB.
It is time to power up that send button to send messages in the message box using WebSockets to the backend server on the chat channel.

var socket = io();
$('#send-message-btn').click(function () {
var msg = $('#message-box').val();
socket.emit('chat', msg);
$('#messages').append($('').text(msg));
$('#message-box').val('');
return false;
});
socket.on('chat', function (msg) {
$('#messages').append($('').text(msg));
});

Line 1

We want to create a socket and we can do that by calling the io() function which is in the socket.io-client.js file.

Line 2

After that, we want to execute a function on the click of the “Send Message” button using the jQuery’s $() function and the click() method.

Line 3

We will get the string value in the message box using jQuery’s $() function and the val() method.

Line 4

We use the emit() function on the socket variable we created in line 1 to send a message on the “chat” channel containing the message box’s value.

Line 5-7

At this point, we will append the message in the message box to the div having messages as its ID, so that the user can see the message was sent. We will assign the value of the message box to an empty string to clear it up.

Line 9-10

We want to append the message received on the chat channel from other users to the div having messages as its ID. The Node.js backend will not resend the message that the client wrote back to itself, but that’s alright because we added the message right away in the click() function handler.
1428464728Sockets-final-screenshot.png

Conclusion

Voila! You have connected your backend and your front-end using WebSockets. If you want to identify the people in the chatroom or add an avatar for each user, it is up to you but you can use this chatroom onward. In the next installment, I will show you how to deploy this anonymous chatroom to Azure and show you how you can debug it.

Stay Tuned for Part 6!

Part 6— The Finale and Debugging Remote Node Apps! is here. You can stay up-to-date on this and other articles by following my twitter account

More Node.js Learning on Azure

For more in-depth learning on node, my course is available here on Microsoft Virtual Academy.
Or some shorter-format videos on similar node subjects:

This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.

Rami Sayar is a technical evangelist at Microsoft Canada focusing on web development (JavaScript, AngularJS, Node.js, HTML5, CSS3, D3.js, Backbone.js, Babylon.js), open data and open source technologies (Python, PHP, Java, Android, Linux, etc.) Read his blog or follow him on Twitter.