1. Getting Started

In this chapter, you dive right into things and install Node.js on your machine and make sure it is working correctly before moving further into the language and writing networked applications. By the end of this chapter, you should have Node set up and running on your computer, have entered a few small test programs to play around with it, and know how to use the built-in Node debugger.

Installing Node.js

Let’s begin by looking at installation on Windows. Mac and Linux users should feel free to skip ahead to the appropriate subsection, unless you have both types of machine.

Installation on Windows

To install Node.js on a Windows machine, you can use the handy installer provided on the nodejs.org website. Visit the Download page and then download the Windows Installer (.msi) for either 32 bits or 64 bits, depending on what platform you are running. I show the installation for Windows 10/64-bit.

After you download the MSI, double-click it. You should see a setup program similar to that shown in Figure 1.1.

Image

Figure 1.1 Windows Setup Installer

Read and accept the License Agreement and then click Install. The install is pretty quick and painless, and a few seconds later, you can click Finish to complete the installation.

Verifying the Installation

To test the installation of the Node software, you can use the Windows command prompt cmd.exe (if you are using PowerShell, that also works just fine). If you are not familiar with the command prompt, you can launch it by going to Start / Run and then typing cmd, as shown in Figure 1.2.

Image

Figure 1.2 Launching the Windows command prompt

You then see a command interpreter, such as in Figure 1.3. If you want to learn more about using the command prompt, search the Internet for help using the phrases “Learning to use Windows cmd.exe” or “Getting Started with PowerShell” (if you are running Windows 7 or later) for more information.

Image

Figure 1.3 The Windows command prompt

To make sure Node was installed properly, type node --version in the command window. You should see the output as in Figure 1.4.

Image

Figure 1.4 Verifying that Node is installed correctly. Check the version number

The command prompt window should print out the version number of Node you just installed a few seconds ago (don’t worry if the number in Figure 1.4 doesn’t match what you see—indeed, I’d be surprised if it did!). If you do not see a version number or if instead you see the output saying that “‘node’ is not recognized as an internal or external command” (see Figure 1.5), something has gone wrong and you should do the following:

Image Look in Control Panel / Programs and see whether the installation is actually completed. If not, try the install again, and pay a bit closer attention to what happens. Perhaps something has gone wrong and there will be an error message.

Image Look in Program Files odejs and make sure node.exe is actually there. If it is not, try installing again (uninstall the old version first, if necessary).

Image Make sure that node.exe is in your PATH environment variable. In the command prompt, Windows has a list of directories in which you can search when you type in the name of a program. You can view this by simply typing path in the command prompt window. It should show something similar to that in Figure 1.6. In particular, look at the two highlighted directory names at the end. Something very similar to both of these should be in your PATH.

Image If Program Files odejs and Users..AppData.. pm are not in your PATH but these folders definitely do exist, you can add them to your PATH manually by adding them to your PATH environment variable. You do this in the System Control Panel window. Click on Advanced System Settings and then Environment Variables. Then add the path of the npm folder (it is in something like C:UsersUserNameLocal pm) to the PATH under User Variables for Username and also add the path to the Node.js folder (it is in something like C:Program Files odejs) to the PATH under System Variables. Note that the npm folder might be in UsernameRemote pm instead of UsernameLocal pm, depending on how your computer is configured.

Image

Figure 1.5 Node is not recognized as an internal or external command

Image

Figure 1.6 Checking your PATH environment variable

After confirming you have node.exe installed and working, you can start writing JavaScript.

Installation on the Mac

Although it’s always possible to build the Node.js software directly from the source code, it’s become sufficiently complex over the last few years that I no longer recommend it and, indeed, just use the package installers provided on the nodejs.org website. I’ll demonstrate this now. If you are extremely keen on building from source, head over to the official Node.js GitHub repository at github.com/nodejs/node and find the instructions there.

Using the PKG Installer

By far the quickest way to install Node.js on your Apple Mac computer running OS X is to download and run the Node PKG installer available from the nodejs.org website.

After you download the installer, double-click it, and you should see something similar to what is shown in Figure 1.7. I tend to use just the default installation because I want all the components, and the default path (/usr/local/bin) is what I want. I recommend you do the same here.

Image

Figure 1.7 Running the Mac PKG installer for Node.js

When the installation is complete, you should see something similar to what is shown in Figure 1.8. As the package installer explains, it is important to make sure that /usr/local/bin is in your PATH environment variable. You can open the Terminal.app program (go to /Applications/Utilities, and launch Terminal). In the terminal window, type

echo $PATH

Image

Figure 1.8 Make sure your path is set up correctly

On my machine, the output is

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/marcw/bin:/usr/local/git/bin

You can see that /usr/local/bin is indeed here in the PATH. If it is not, you should edit your ~/.bash_profile file (it’s okay to create this file if it does not exist) and add

PATH=${PATH}:/usr/local/bin

Close the terminal window, launch another, and verify that /usr/local/bin is now in your PATH. You should be able to type

node --version
npm --version

and see something like

client:LearningNode marcw$ node --version
v6.3.1
client:LearningNode marcw$ npm --version
3.10.3

Don’t worry if the version number above doesn’t match what you have on your computer.

After confirming you have the node program installed and working, you can start writing JavaScript.

Installation on Linux

Installing Node.js

Although I used to build Node.js on Linux from source in the past, this has become sufficiently complex over the last few years that I’ve switched to just using the prebuilt binary packages provided on the nodejs.org website. For those super keen on building from the source code, head on over to github.com/nodejs/node for instructions on how to do this.

First, go to the nodejs.org website and download the appropriate tarball (archive package ending in .tar.xz) for your platform listed under “Linux Binaries”..” This will leave you with a file of the form node-vX.Y.Z-linux-x64.tar.xz. This archive contains everything in the right place, so basically we just need to copy it to an appropriate location and use it from there. Here is what I usually do:

marcw@hostname:~$ cd ~/bin
marcw@hostname:~$ tar xz ~/Downloads/node-vX.Y.Z-linux-x64.tar.xz
marcw@hostname:~$ PATH=$PATH:~/bin/node-vX.Y.Z-linux-x64

If ~/bin does not exist, I create it first. It will become a hassle to type in the PATH=... line every time you start a new terminal, so you should actually edit your .bash_profile file (or the equivalent for your current shell) and include that line in there.

When you are done, you should be able to just enter

node --version
npm --version

and get output somewhat similar to

marcw@hostname:~$ node --version
v6.3.1
marcw@hostname:~$ npm --version
3.10.3

Running Node.js and “Hello World!”

There are two primary ways to use Node.js on your machines: by using the Node shell or by saving JavaScript to files and running those.

The Node Shell

The first way you will run Node.js is the Node shell, which is frequently called the Node REPL—REPL stands for Read-Eval-Print-Loop. It’s a great way to quickly test things in Node. If you don’t remember exactly how a function should be used, you can just quickly use the REPL and type in something to see what happens.

To launch the Node shell, you simply type node in whatever shell you are using:

marcw@hostname:~$ node
>

The > is all the response you get. You can immediately start typing in some code:

> console.log("Hello World!");
Hello World!
undefined
>

The first line of the output is the result of the code you just executed. In this case, you use the Node global variable console and its log function to print out Hello World! (see the next chapter for more information on console and other globals). The output of this statement is, predictably, Hello World!, which is printed for you.

The last line of the output is always the resulting value of the preceding statement. Every statement, function call, or expression has a value associated with it, which is printed out in the Node shell for you. If there is no evaluated expression value or the called function does not return any particular value, the special value undefined is returned instead.

To exit the REPL, you simply press Ctrl+D (same on Windows).

If you ever see three dots (...) in the Node REPL, that means it is expecting more input from you to complete the current expression, statement, or function. If you do not quite understand why it is giving you the ellipsis, you can just type .break (with the period) to get out of it:

> function () {
... }
... what?
... .break
>

Editing and Running JavaScript Files

The other option for running Node.js code is to simply use your favorite text editor to write JavaScript code into a file and then run that code via the command line using the node command.

To demonstrate this, save the following to a file called hello.js:

/**
 * Let's be sociable.
 */
console.log("Hello World!");

Now, you can execute this file from the command line with

node hello.js

And you should see this output:

Hello World!

Because you are not in the Node shell, you don’t get any information on the return values of the code executed.

Your First Web Server

You’re ready to write something a bit more interesting now and create a little web server. Fortunately, Node makes this task extremely easy. Enter and save the following into a file called web.js:

var http = require("http");

function process_request(req, res) {
    var body = 'Thanks for calling! ';
    var content_length = body.length;
    res.writeHead(200, {
        'Content-Length': content_length,
        'Content-Type': 'text/plain'
    });
    res.end(body);
}

var s = http.createServer(process_request);
s.listen(8080);

To run it, simply type

node web.js

Your computer now has a web server running on port 8080. To test it, you can use the command-line program curl, which most Mac and Linux machines have preinstalled (Windows users, see “Downloading from the Web on Windows”). (You also can just type http://localhost:8080 into a web browser, but you won’t see the response codes there unless you open a debug console).

curl -i http://localhost:8080

You should now see something similar to the following:

HTTP/1.1 200 OK
Content-Length: 20
Content-Type: text/plain
Date: Tue, 15 Feb 2013 03:05:08 GMT
Connection: keep-alive

Thanks for calling!

Node.js provides a lot of powerful functionality right out of the box, and in the first line of the preceding program, you use one of these built-in modules—the http module, which allows your program to act as a web server. The require function includes this module, and you have the variable http to refer to it.

The createServer function takes only one argument, and that is a function that will be called each and every time somebody makes a connection to your server. You pass the process_request function you wrote earlier, which is called with two parameters: an object representing the incoming request (a ServerRequest object) and another for the pending response (of type ServerResponse). Once the server is created, you tell it to start listening for incoming requests on a particular port—here, you use 8080—when you launch the program.

The -i switch you passed to curl earlier tells it to print out the headers along with the response. This lets you learn a little bit more about what exactly Node is doing for you.

You can see that the 200 (OK) response you passed to the ServerResponse#writeHead function is returned in the HTTP response headers, and you also see the content length and types are both represented. Node.js, by default, also indicates that HTTP connections to its server are keep-alive, which allows multiple requests on the same network connection; you don’t need it for most of the examples early in this book.

To stop the server from running, you simply press Ctrl+C. It is smart enough to clean up everything and shut down properly.

Debugging Your Node.js Programs

Now you can rewrite the preceding web server, but this time get a little careless and introduce a smelling pistake—misspell body.length, as follows—and put it into a file called debugging.js:

var http = require("http");

var s = http.createServer(function (req, res) {
    var body = 'Thanks for calling! ';
    var content_length = body.lengtth;
    res.writeHead(200, {
        'Content-Length': content_length,
        'Content-Type': 'text/plain'
    });
    res.end(body);
});

/**
 * Now run the server, listening on port 8080
 */
s.listen(8080);

You can run this program as before:

node debugging.js

Now, when you connect to http://localhost:8080, you’ll probably see something like this:

client:~ marcw$ curl -i localhost:8080
HTTP/1.1 200 OK
Content-Length: undefined
Content-Type: text/plain
Date: Tue, 30 Oct 2012 04:42:44 GMT
Connection: keep-alive

You no longer get the "Thanks for calling!" message, and you can see that the Content-Length header is not what you expected.

For a trivial program like this, the error is pretty easy to figure out, but in a bigger program, it can be hard to determine what exactly has gone wrong. To help with this issue, Node.js includes a debugger right in the node program. To use it, you just add the debug flag before the name of your program:

node debug debugging.js

You should see something like the following:

client:Chapter01 marcw$ node debug debugging.js
< debugger listening on port 5858
connecting... ok
break in debugging.js:1
  1 var http = require("http");
  2
  3 function process_request(req, res) {
debug>

You use a few key commands in the Node debugger:

Image cont—Continue running.

Image next—Step over the next statement.

Image step—Step into the next statement (if possible; otherwise, just step over).

Image out—Step out of the currently executing function.

Image backtrace—Show the current call execution frame or call stack.

Image repl—Start the Node REPL to allow you to view variable values and execute code.

Image watch(expr)—Add the given expression to the watch list, which is shown whenever you step or move through anything in the debugger.

Image list(n)—List the n lines of source code before and after the currently stopped line in the debugger.

Now, suspecting something might be wrong with the Content-Length in the program, you can put a breakpoint on the line var content_length = body.lengtthlenggth;, or line 5:

debug> setBreakpoint(5)
  1 var http = require("http");
  2
  3 function process_request(req, res) {
  4     var body = 'Thanks for calling! ';
* 5     var content_length = body.lenggth;
  6     res.writeHead(200, {
debug>

Line 5 now has a * next to it to indicate there is a breakpoint. When you start the debugger, the program is stopped at the first line. You can resume execution by using the cont command:

debug> cont
debug>

Now, you go to another terminal window or command prompt and type

curl -i http://localhost:8080

You should immediately notice two things:

1. The curl does not return right away.

2. In your node debug session, you now see

break in debugging.js:5
  3 function process_request(req, res) {
  4     var body = 'Thanks for calling! ';
> 5     var content_length = body.lenggth;
  6     res.writeHead(200, {
  7         'Content-Length': content_length,

You can skip over this line:

debug> next
break in debugging.js:7
* 5     var content_length = body.lenggth;
> 6     res.writeHead(200, {
  7         'Content-Length': content_length,
  8         'Content-Type': 'text/plain'
  9     });

And now start the Node REPL so you can examine some variable values:

debug> repl
Press Ctrl + C to leave debug repl
>

Let’s look at the values of body and content_length, respectively:

> body
'Thanks for calling! '
> content_length
>

For body, you can see, as expected, that you get a value. But for content_length, which you expect to be 20, you see nothing. You can now see that the code that set its value is wrong and have found the problem!

Finally, you can either just shut down the whole system by pressing Ctrl+D to end the debugger, or you can type cont to continue running the server. Typing cont inside the REPL will not work and results in the following error: “ReferenceError: cont is not defined.” You will need to press Ctrl+C to exit the REPL first, and then you can use cont.

Although this introduction to the debugger has been a quite brief, it is worth playing around with; it is quite powerful and very useful. There are, additionally, some other browser-based debuggers being written by Node.js community members, the most promising of which so far is node-inspector. Feel free to search for them and play around with them to see how they can help you.

In a pinch, there is nothing wrong with inserting a simple console.log(variable_name); into your code to have the results printed to the terminal window. It can often be a quick and simple way to get the information you need to track down bugs or problems.

Staying Up-to-Date and Finding Help

As mentioned previously, one of the challenges of working with Node.js is its constant state of change. Although more and more APIs and sections of the product are considered Stable or Locked, some things are still changing with every new release, and these releases are happening on a weekly basis.

Here are some things you can do to keep up-to-date and not miss out on any important changes or news:

Image Join the Node.js mailing list at http://groups.google.com/group/nodejs. Many of the core Node developers are on this list and post whenever a new release or change is made.

Image If you are on Twitter, follow @nodejs there; you will receive tweets whenever there is a new release or whenever something else important comes along.

Image Visit nodejs.org on a semiregular basis to make sure you are not falling too far behind.

For help, the nodejs Google group is, of course, invaluable, as is the nodejs.org website. Similarly, StackOverflow.com has a very active community helping out with Node-related questions, and you can find many good answers there.

However, I have found that a vast majority of problems are best answered with a simple Internet search. Somebody somewhere has very likely run into the same problem as you and written a blog post or message about it. It is quite rare that I am unable to find the answers with simple searches.

Summary

You should now have Node.js installed on your computer, verified that it is working properly, and even run and debugged a few problems. Now it’s time to take a closer look at the JavaScript language.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset