An Introduction to node.js
In this article, I’m going to explore node and progress through the basic concepts needed to develop with it. By the end of the article not only will you have a functioning chat server, you’ll understand enough to take the sample code and enhance it on your own. I hope you’ll be pleasantly surprised at how easy it is.
With node.js, the world is pretty clearly divided. Its development is done completely in Linux or Mac OSX, and a massive majority of its community works in the same environments. There has been very little attention given to Windows until recently, and some versions of node were impossible to run. Luckily, while doing the work for this section of the article, I found a relatively simple solution to running node on Windows that is unobtrusive and just works. There are some slight differences that you will have to contend with when running node on Windows, but I will address them when they are needed. The following subsections give installation instructions.
In Windows, use the following steps to install node:
- Go to http://www.rafaljonca.org/d/nodejs-windows and download the NodeJS 0.4.1 package.
- The built-in Windows extractor won’t work, since the package is in 7-zip format. Download an extractor that will work if you need to. For a free one, go to http://7-zip.org/.
- You can extract it anywhere, I just put it on my Desktop.
- Open up a PowerShell prompt with administrator privileges and navigate to the bin folder in the distribution you just extracted.
- Execute ./shell.cmd.
Please note that every time you open a new PowerShell prompt to use node, you will need to execute the shell.cmd file as outlined in step 5.
In OSX, use the following steps to install node:
- Go to http://sites.google.com/site/nodejsmacosx/ and download the NodeJS-0.4.1.pkg file.
- Install the package.
- Open your shell of choice.
Type the following command and make sure you get matching output:> node -v
There are some alternate ways to install node.js both on Windows and OSX. You can see them on the node.js wiki https://github.com/joyent/node/wiki/Installation.
Let’s take a look at a simple node.js program. Open your favorite IDE or text editor and create a file called flyingMonkeys.js, and then type in the code from the following code snippet and save the file:// Simple console logging.
// It works the same way it would in a web browser
console.log('Look! Flying monkeys!');
To run programs in node, you’ll go back to your trusty command-line tool and type the following command: (note: if you have installed node using the Windows instructions I provided above, make sure that you have executed ./shell.cmd):> node flyingMonkeys.js
Look! Flying monkeys!
Hooray! OK, now that the ubiquitous “Hello, world!” app is out of the way, let’s look at a comparison of the behavior between node and the browser.
By: Brian Mavity