Node.js for True Beginners

Node.js for True BeginnersI remember trying to get into starting with Node.js months ago and, to be frank, it wasn't the simplest process. Installation was a hassle, and pretty much required the use of a Linux of Mac computer. Now, Node.js has evolved to the point where just about anyone can get started using Node.js (maybe not my grandparents, but they don't even have a computer). Let's get started!

Installing Node.js

Seriously though, Node.js has come a long way in the past few months, especially in terms of getting it up and running on your computer. Now, you can just hop on over to http://nodejs.org/#download and click the link for the installer that you wish to use. If you're using 64-bit Windows, make sure you notice the link lower down labeled "Windows x64 Installer". After it's downloaded, just run it, follow the prompts, and Node will be installed and working on your computer. To be sure that it's working open up a terminal window (in Linux or Mac, start up the Terminal, and on Windows use Windows Powershell – if you have it – or a normal command prompt). Inside here just type in "npm". It should give you instructions on how NPM should be used. Then just type in "node". It should just give you an angle bracket pointing to the right. This means that you're inside the Node REPL, which means Node is working.

The REPL

While you're inside the REPL, you can write any JavaScript code and it will be executed immediately. If you want to write a multi-line function or something, you can do that the same way you would in a text editor: normally when you hit Enter, it executes the code, but if you haven't closed a bracket or parenthesis, it'll just create a new line that starts with an ellipsis (...) signifying that you can keep writing. Basically just treat this almost exactly the same way that you would a console in the browser, with 2 very distinct differences:

  1. The environment: you are not in the browser. You do not have access to any sort of DOM. You don't even have the window global. Instead there are several globals and all other variables are localized to files/modules.
  2. There are built in commands for the REPL that allow you to use it more like a standard command prompt. If you type in .help, which is one of the commands, you'll see a list of commands that can be used.

Here's the point where you stop reading and go play around for a couple hours and then come back. =)

Your First Node.js Web App

As with any starter tutorial we need to create a Hello World application. Of course this is going to be a web app, but you'll realize soon enough that Node.js is for far more than web apps. It allows JavaScript developers to create command-line utilities entirely with JavaScript. But, we won't get to that today. Today, we're going to make a super awesome all-I-say-is-"hello" application.

To start out, create a file anywhere you wish called "app.js" (or anything you want really; it doesn't even need the .js extension if you don't want it). Now open it up in whatever editor you have deemed worthy of being a JavaScript editor and type in the following code:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

Save it and then jump back to the terminal (if you even left it). Make sure you're inside the directory where you created the file. Now type in node app.js (make sure to replace app.js with the name of the file you created if you were cool enough to use an alternate file name). Great! Now your tiny little server is running. Navigate your browser on over to http://127.0.0.1:1337/ to see your message!

Now let's walk through the code here. The first line calls require, which is a global function that just loads a file named http.js. If this file isn't found in the current directory, it'll pull it from the standard libraries that come with Node.js. When you require a script, it returns a value that the is specified within the file you pulled in. In this case, you get an object that represents an HTTP server. The next thing we do is create a server.  That's right, servers are constructed with JavaScript, instead of relying on third-party servers such as Apache or IIS. This makes things a bit more complicated to start out, but gives you all the power and allows the server to be set up differently for each application easily.

Anyway, createServer takes a callback function that is executed every time the server receives a request and it sends objects representing the request and response into that callback function. createServer also returns a server object. Now let's take a look at the contents of the callback. Notice, we never touch the request object. With a good server used for real applications, we would take a look at the request and pull information like the path and query parameters to determine what should be returned, but here we don't care. In fact you could navigate your browser to http://127.0.0.1:1337/any/path/you/want?and=any&params and it would still show the "Hello World" message.

We do work with res though. First we call writeHead on it, which sets headers for the response. Here we're sending a 200 status and setting the content type to plain text. Next we call end, which means we've reached the end of the response so nothing more can be added to it and it should be shipped out to the requester. We could have also written that line like this:

res.write("Hello World\n");
res.end();

In other words, calling end is just like calling write and then ending the response. The write method just writes more data to the response. Now, we're done with the callback, so we call listen on the server. listen takes a port number and an IP address to listen to for requests. When it receives a request there, it calls the callback that we just finished creating. By using listen, we create an event listener, which keeps the JavaScript running and waiting, even after the entire file has executed. You'll notice that if you ran node app.js that it didn't go back to the normal command prompt line after it finished executing because the process is still running and waiting for requests. If you want to stop the server hit Ctrl/Cmd + C, which will break the execution of the process.

The last thing we do in app.js is a simple console.log, which signals use that the server is indeed running. If we didn't do this we'd just see a blank line in the console until we terminated the process.

Conclusion

This may be the end of this tutorial, but there's still tons more to learn about Node.js. Previously you saw Mike M. Lin's tutorial on getting started with Express, which is a nice framework for simplifying the setup and development of Node-based sites, but I'm not so sure that it's my cup of tea. I still have a few more things related to Node to talk about before I get into any higher level development, but eventually I should be looking at at least one framework.  I hope you're all looking forward to more. God Bless and Happy Coding!

About the Author

Author: Joe Zim

Joe Zim

Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.


  • Tim Jones

    Thanks, Joe! Very helpful! I had tried a couple of times to get Node.js running without success, but your step-by-step process got me going!

    Are there any “must-have” NPM modules that recommend for those of us just getting started?

    Tim

    • http://www.joezimjs.com Joe Zimmerman

      That should be coming up in future articles.

  • ND

    Oh really, Its very helpful to me.

    Now i get my first program that run on http://127.0.0.1:8080/

  • Gurinder Singh

    Hey man i want your help actually i dnt kno any thing abt node js but yes i have installed it and created my first program with the help of your above example……now the point is a company wants me to create a chat server within 10 days in node js and said use db mongo,,, i am good in java but new to node js help me how can i do this please help i dnt want to lose dat job

    • http://www.joezimjs.com Joe Zimmerman

      Hi,

      If you’re looking to do a chat application, you’re going to want to use http://socket.io/. Look around on Youtube for “socket.io and nodejs” and I’m sure you’ll find plenty of example applications to build off of.

      I, myself, have yet to use MongoDB, though I plan to in the future. I can’t give any help there, but once again there are countless tutorials around the net.

      Finally, as much as I’d love to help you more, this is not a place to get free personal training. This is a place where I (and any other good developers who wish to) present some of the knowledge I want to share with the world. A full chat application is not something I would just give away for free unless it was a very simple one. If you don’t know how to do something, try to learn it by looking it up. If you still can’t figure it out, it might just be time to consider a career change or tell your boss that you don’t have the expertise to accomplish it in 10 days.

      • Gurinder Singh

        Thanx man :)