官术网_书友最值得收藏!

Run a few commands; testing the commands

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

Node's command-line tools

The basic install of Node includes two commands, node and node-waf. We've already seen node in action. It's used either for running command-line scripts or server processes. The other, node-waf, is a build tool for Node native extensions. Since it's for building native extensions, we will not cover it in this book and you should consult the online documentation at nodejs.org.

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

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

Options:
 -v, --version print node's version
 -e, --eval script evaluate script
 -p, --print print result of --eval
 -i, --interactive always enter the REPL even if stdin
 does not appear to be a terminal
 --no-deprecation silence deprecation warnings
 --trace-deprecation show stack traces on deprecations
 --v8-options print v8 command line options
 --max-stack-size=val set max v8 stack size (bytes)

Environment variables:
NODE_PATH ':'-separated list of directories
 prefixed to the module search path.
NODE_MODULE_CONTEXTS Set to 1 to load modules in their own
 global contexts.
NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL

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

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

Notice that there are options for both Node and V8 (not shown in the previous command line). Remember that Node is built on top of V8; it has its own universe of options that largely focus on details of bytecode compilation or the 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.

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

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

Any code you can write in a Node 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

Now let's see how to run scripts with Node. It's quite simple. Let's start by referring back to the help message:

$ node –-help
Usage: node [options] script.js [arguments]

It's just a script filename and some script arguments, which should be familiar for anyone who has written scripts in other languages.

Creating and editing Node scripts can be done with any text editor that deals with plain text files, such as vi/Vim, Emacs, Notepad++, jEdit, BBEdit, 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 the book, it doesn't really matter where you put the files. However, for neatness' sake, you could start by making a directory named node-web-dev in the home directory of your computer, then inside that create 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
app.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 analog 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 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]);
}

And you can run it as follows:

$ node ls2.js ~/node/0.10.7/bin
node
node-waf
npm

Launching a server with Node

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, we want to run a simple HTTP server. Let's borrow the simple server script on the Node 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!\n');
}).listen(8124, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8124');

And 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. If you're interested in how it works, flip forward from Chapter 4, HTTP Servers and Clients - A Web Application's First Steps to Chapter 6, Data Storage and Retrieval. 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 exited. In both cases, execution of the script reaches the end of the script; in app.js, the Node process does not exit, while in ls.js it does. The reason is the presence of active event listeners. Node always starts up an event loop, and in app.js the listen function creates an event listener which implements the HTTP protocol. This event listener keeps app.js running until you do something such as press Ctrl + 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, Node will exit.

主站蜘蛛池模板: 文成县| 崇阳县| 宜都市| 克山县| 隆昌县| 温泉县| 宝山区| 阜平县| 怀安县| 互助| 苏尼特左旗| 蒙山县| 都江堰市| 历史| 建湖县| 临朐县| 通州市| 冀州市| 阜新| 清徐县| 吉木萨尔县| 喀喇沁旗| 深州市| 陆川县| 诸暨市| 弥勒县| 浏阳市| 宣化县| 芜湖县| 长海县| 阿图什市| 类乌齐县| 孟州市| 紫云| 开平市| 门源| 平湖市| 深圳市| 淳化县| 二连浩特市| 中江县|