Running and testing commands

Now that you've installed Node.js, we want to do two things—verify that the installation was successful and familiarize you with the command-line tools.

Node.js's command-line tools

The basic install of Node.js includes two commands, node and npm. We've already seen the node command in action. It's used either for running command-line scripts or server processes. The other, npm, is a package manager for Node.js.

The easiest way to verify that your Node.js installation works is also the best way to get help with Node.js. Type the following command:

$ node --help
Usage: node [options] [ -e script | script.js ] [arguments] 
       node debug script.js [arguments] 

Options:
  -v, --version         print Node.js version
  -e, --eval script     evaluate script
  -p, --print           evaluate script and print result
  -c, --check           syntax check script without executing
  -i, --interactive     always enter the REPL even if stdin
                        does not appear to be a terminal
  -r, --require         module to preload (option can be repeated)
  --no-deprecation      silence deprecation warnings
  --trace-deprecation   show stack traces on deprecations
  --throw-deprecation   throw an exception anytime a deprecated function is used
  --trace-sync-io       show stack trace when use of sync IO
                        is detected after the first tick
  --track-heap-objects  track heap object allocations for heap snapshots
  --prof-process        process v8 profiler output generated
                        using --prof
  --v8-options          print v8 command line options
  --tls-cipher-list=val use an alternative default TLS cipher list
  --icu-data-dir=dir    set ICU data load path to dir
                        (overrides NODE_ICU_DATA)

Environment variables:
NODE_PATH                ':'-separated list of directories
                         prefixed to the module search path.
NODE_DISABLE_COLORS      set to 1 to disable colors in the REPL
NODE_ICU_DATA            data path for ICU (Intl object) data
NODE_REPL_HISTORY        path to the persistent REPL history file

Documentation can be found at https://nodejs.org/

It prints the USAGE message giving you the command-line options.

Note that there are options for both Node.js and V8 (not shown in the previous command line). Remember that Node.js is built on top of V8; it has its own universe of options that largely focus on details of bytecode compilation or garbage collection and heap algorithms. Enter node --v8-options to see the full list of them.

On the command line, you can specify options, a single script file, and a list of arguments to that script. We'll discuss script arguments further in the next section, Running a simple script with Node.js.

Running Node.js with no arguments plops you in an interactive JavaScript shell:

$ node
> console.log('Hello, world!');
Hello, world!
undefined

Any code you can write in a Node.js script can be written here. The command interpreter gives a good terminal-orientated user experience and is useful for interactively playing with your code. You do play with your code, don't you? Good!

Running a simple script with Node.js

Now let's see how to run scripts with Node.js. It's quite simple and let's start by referring back to the help message shown above. It's just a script filename and some script arguments, which should be familiar for anyone who has written scripts in other languages.

Tip

Creating and editing Node.js scripts can be done with any text editor that deals with plain text files, such as VI/VIM, Emacs, Notepad++, Jedit, BB Edit, TextMate, or Komodo. It's helpful if it's a programmer-oriented editor, if only for the syntax coloring.

For this and other examples in this book, it doesn't truly matter where you put the files. However, for the sake of neatness, you can start by making a directory named node-web-dev in the home directory of your computer, and then inside that creating one directory per chapter (for example, chap02 and chap03).

First, create a text file named ls.js with the following content:

var fs = require('fs');
var files = fs.readdirSync('.');
for (fn in files) {
  console.log(files[fn]);
}

Next, run it by typing the following command:

$ node ls.js
ls.js

This is a pale cheap imitation of the Unix ls command (as if you couldn't figure that out from the name). The readdirSync function is a close analogue to the Unix readdir system call (type man 3 readdir in a terminal window to learn more) and is used to list the files in a directory.

The script arguments land in a global array named process.argv, and you can modify ls.js, copying it as ls2.js, as follows to see how this array works:

var fs = require('fs');
var dir = '.';
if (process.argv[2]) dir = process.argv[2];
var files = fs.readdirSync(dir);
for (fn in files) {
  console.log(files[fn]);
}

You can run it as follows:

$ node ls2 ~/.nvm/versions/node/v5.5.0/bin
node
npm

Launching a server with Node.js

Many scripts that you'll run are server processes. We'll be running lots of these scripts later on. Since we're still in the dual mode of verifying the installation and familiarizing you with using Node.js, we want to run a simple HTTP server. Let's borrow the simple serverscript on the Node.js home page (http://nodejs.org).

Create a file named app.js containing the following:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello, World!
');
}).listen(8124, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8124');

Run it this way:

$ node app.js
Server running at http://127.0.0.1:8124

This is the simplest of web servers you can build with Node.js. If you're interested in how it works, flip forward to Chapter 4, HTTP Servers and Clients – A Web Application's First Steps; Chapter 5, Your First Express Application; and Chapter 6, Implementing the Mobile-First Paradigm. At the moment just visit http://127.0.0.1:8124 in your browser to see the "Hello, World!" message.

A question to ponder is why this script did not exit when ls.js did exit. In both cases, execution of the script reaches the end of the script; the Node.js process does not exit in app.js, while in ls.js it does.

The reason is the presence of active event listeners. Node.js always starts up an event loop, and in app.js, the listen function creates an event listener that implements the HTTP protocol. This event listener keeps app.js running until you do something like typing Control-C in the terminal window. In ls.js, there is nothing that creates a long-running event listener, so when ls.js reaches the end of its script, the node process will exit.

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

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