- Node Web Development(Second Edition)
- David Herron
- 966字
- 2021-08-13 16:46:53
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.
- 垃圾回收的算法與實現
- Android Development with Kotlin
- Object-Oriented JavaScript(Second Edition)
- Ray分布式機器學習:利用Ray進行大模型的數據處理、訓練、推理和部署
- Securing WebLogic Server 12c
- Big Data Analytics
- Node.js全程實例
- Android系統原理及開發要點詳解
- Java面向對象程序設計
- Test-Driven Development with Django
- SQL Server 2008 R2數據庫技術及應用(第3版)
- 代碼閱讀
- Java程序設計基礎(第6版)
- Data Science Algorithms in a Week
- Learning Concurrency in Python