Getting Started with Node.js for Windows

By March 18, 2014 JavaScript No Comments

With the recent announcements of Paypal and Netflix moving to Node.js, the server-side JavaScript platform has proven itself worthy to enterprises. It’s one small step for Node, one giant leap for JavaScript! From developers of .NET, Java, PHP, Ruby on Rails, and more, all walks of server-side coders are converging to the platform. And as bigger players like Yahoo, Walmart, and Oracle join the table, Node is loosing its reputation as being intrinsically immature and unstable. In this post, I would like to show you how easy it is to set up Node.js in a Windows world.

Installing Node.js

Getting Node.js installed on Windows is a breeze. Go to Node.js and download and run the “.msi” file. This will install Node.js and NPM (Node Packaged Modules). NPM is equivalent to NuGet package manager for .NET apps.

Running Node.js

Running Node.js on Windows is a breeze too. Open up PowerShell and type “node -v” to ensure that Node is in your environment variables and to see the version of Node.js you are running. Also type “npm -v” to see the Node Packaged Managed version installed. Are you good? Ok, let the fun begin!!

Open up notepad and we will build our first Node.js app. Paste the following and call it anything, such as “example.js“, and save it to a folder you wish:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node');
}).listen(1337, '127.0.0.1');

Now back to PowerShell. Change the directory to folder of your “example.js” file and run Node!

cd C:\Websites\NodeTest
node example.js

Fire up your browser and go to http://127.0.0.1:1337. Did it work? Congrats you ran your first Node.js app!

Serving a Website

You thought I’d leave you with a “Hello World” example and call it a day? It would be more beneficial if we knew how to run an HTML file. Add an “index.html” file with any HTML in it. This will do:

<html>
  <head>
    <title>Sample Node.js Website</title>
  </head>
  <body>
    <p>This is the home page for you Node.js website.</p>
  </body>
</html>

Time to run the app. Create a new file called anything, such as “index.js“, and add the following JavaScript code to it:

var http = require('http');
var fs = require('fs');
 
http.createServer(function(req, res){
    fs.readFile('index.html',function (err, data){
        res.writeHead(200, {
             'Content-Type': 'text/html',
             'Content-Length': data.length
           });
        res.write(data);
        res.end();
    });
}).listen(1337, '127.0.0.1');

Things are getting more interesting here. Notice there are more “require” lines at the top. You are pulling in dependencies that your app will need. This is like the “using” namespace directives in C# to call in dependencies.

Run “index.js” from PowerShell by typing: node index.js (dont forget to hit Ctrl-C to quit the last Node app or use a different port number this time). In your browser, go to http://127.0.0.1:1337 and you should see your HTML file. You will probably feel excited on the achievements, but if you were like me, had mixed feelings about it. This is low level coding and if I had to think about reading/streaming files and what status codes to send out every time, it’s going to get boring pretty fast. Say hello to ExpressJS!

Using Node Package Manager

Node.js has a companion that makes everything feel right again. ExpressJS takes away the boilerplates in Node.js and let’s you cut straight to web development. It is a web framework that allows you to build single, multi-page, and hybrid web applications. You can’t go very far with Node.js without it!

First use NPM to install it. To do this, open PowerShell again and change to your app’s directory again. Now type:
npm install express. This will install ExpressJS by creating a folder called “node_modules“. From this point on, your Node modules will be put in there, kind of like your “bin” folder for .NET applications, where you call or “require” your dependencies from.

Getting Started with ExpressJS

Now create any new file, such as “server.js“, and paste in the following:

var express = require('express');
 
//CREATE APP
var app = express();
 
//LOCATION OF STATIC CONTENT IN YOUR FILESYSTEM
app.use(express.static(__dirname));
 
//PORT TO LISTEN TO
app.listen(1337);

This is calling the depenency of ExpressJS, then creating an app from it. From there you are ready to rock and roll! In this case, we are simply serving static files. The “__dirname” is a special variable from ExpressJS that means the root file system location. Finally you tell the app to listen to port 1337. Now you have a Node.js website serving static files! Add a few extra HTML files with even some in sub-folders, then go to http://127.0.0.1:1337 to test it out.

What About IIS

In these examples, I kept running the app from post 1337 instead of port 80. The reason is because IIS is already listening to port 80. There are a couple of ways to make IIS and Node.js live in perfect harmony:

  • IISNode: This is a clever idea to run Node.js as an application pool for your IIS websites, much like running PHP in IIS. As a matter of fact, Azure uses this to run Node.js on its platform.
  • WinServ: This runs Node.js as a Windows service. It is actually a Node.js friendly wrapper around the popular NSSM (Non-Sucking Service Manager). Once running as a service, you can use IIS’s Application Request Routing (ARR) to proxy requests to your Node.js app’s port.

What About MS SQL

There are several MS SQL drivers for Node.js, some are even cross-platform. One that only works in a Windows environment is released by Windows Azure: Microsoft Driver for Node.js for SQL Server. Then you can start doing things like this:

var sql = require('node-sqlserver');
var connStr = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
var cmd = "SELECT TOP 10 FirstName, LastName FROM Person.Person";
 
sql.open(connStr, function (err, conn) {
    conn.queryRaw(cmd , function (err, results) {
        for (var i = 0; i < results.rows.length; i++) {
            console.log(
                   "FirstName: " + results.rows[i][0]
             + " LastName: " + results.rows[i][1]);
        }
    });
});

Conclusion

This is only scratching the surface! Armed with ExpressJS, you’ll be able to create full-fledged MVC applications with routers, views, layouts, services, and so much more. Also, unless you need to integrate with existing Microsoft applications or MS SQL databases, MongoDB is a great companion to creating a Node stack and will help you free yourself from the rigidness of SQL. Finally, you can create a mean JavaSript full stack using MEAN, which is MongoDB, ExpressJS, AngularJS, and Node.js. Now that Enterprises have cozied up to Node.js, isn’t it time for you to do the same?

Happy Coding!!



References

The following two tabs change content below.

Basem Emara

Software Architect at Falafel Software
Basem has over 10 years experience as a consultant and developer for dozens of projects for educational, advocacy, non-profit, small business, enterprise, and governmental organizations. As an innovator who recognizes and leverages the power of the web, he has been able to help real estate agencies, schools, hospitals, wholesale distributors, shipping carriers, and other businesses pioneer their industries utilizing the best that today’s technology has to offer from a more creative point of view. Simple yet elegant is the key to his approach, as well as the belief that continual process improvement is always possible.