chapter1 THE SETUP

INSTALLING NODE.JS IS a painless process.Since its conception, one of its goals has been maintaining a small number of dependencies that would make the compilation or installation of the project very seamless.

This chapter describes the installation process for Windows, OS X, and Linux systems. For the latter, you’re going to ensure that you have the correct dependencies and compile it from the source.

Note: When you see lines prefxed with $ in the code snippets in the book, you should type these expressions into your OS shell.

INSTALLING ON WINDOWS

On Windows, go to http://nodejs.org and download the MSI installer. Every release of node has a corresponding MSI installer that you need to download and execute.

The filename follows the format node-v?.?.?.msi. Upon executing it, simply follow the instructions in the setup wizard shown in Figure 1-1.

To ensure that the installation worked, openthe shell or command prompt by running cmd.exe and typing $ node –version.

The version name of the package you just installed should display.

 

 

INSTALLING ON OS X

On the Mac, similarly to Windows, you can leverage an installer package. From the Node.JS website, download the PKG fle that follows the format node-v?.?.?.pkg. If you want to compile it instead, ensure you have XCode installed and follow the Compilation instructions for Linux.

Run the downloaded package and follow the simple steps (see Figure 1-2).

To ensure installation was successful, open the shell or terminal by running Terminal.app (you can type in “Terminal” in Spotlight to locate it) and type in $ node –version.

Te version of Node you just installed should be outputted.


 

INSTALLING ON LINUX

Compiling Node.JS is almost just as easy as installing binaries. To compile it in most *nix systems, simply make sure a C/C++ compiler and the OpenSSL libraries are available.

Most Linux distributions come with a package manager that allows for the easy installation of these.

For example, for Amazon Linux, you use

> sudo yum install gcc gcc-c++ openssl-devel curl

On Ubuntu, the installation is slightly diferent; you use

> sudo apt-get install g++ libssl-dev apache2-utils curl

COMPILING

From your OS terminal, execute the following commands:

Note: Replace ? with the latest available version of node in the following example.

$ curl -O http://nodejs.org/dist/node-v?.?.?.tar.gz

$ tar -xzvf node-v?.?.?.tar.gz

$ cd node-v?.?.?

$ ./configure

$ make

$ make test

$ make install

If the make test command aborts with errors, I recommend you stop the installation and post a log of the ./configure, make, and make test commands to the Node.JS mailing list.

ENSURING THAT IT WORKS

Launch a terminal or equivalent, such as XTerm, and type in $ node –version.

Te version of Node you just installed should be outputted.

THE NODE REPL

To run the Node REPL, simply type node.

Try running some JavaScript expressions. For example:

> Object.keys(global)

Note: When you see lines prefxed with > in the code snippets in the book, you should run these expressions in the REPL.

The REPL is one of my favorite tools for quickly verifying that diferent Node or vanilla JavaScript APIs work as expected. While developing larger modules, it’s ofen useful to check a certain API works exactly the way you remember it when unsure. To that end, opening a separate terminal tab and quickly evaluating some JavaScript primitives in a REPL helps immensely.

EXECUTING A FILE

Like most scripted programming languages, Node can interpret the contents of a fle by appending a path to the node command.

With your favorite text editor, create a fle called my-web-server.js, with the following contents:

var http = require('http');
var serv = http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<marquee>Smashing Node!</marquee>');
});
serv.listen(3000);
 Run the fle:

$ node my-web-server.js

Then, as shown in Figure 1-3, point your web browser to http://localhost:3000.

In this code snippet, you’re leveraging the power of Node to script a fully compliant HTTP server that serves a basic HTML document. This is the traditional example used whenever Node.JS is being discussed, because it demonstrates the power of creating a web server just like Apache or IIS with only a few lines of JavaScript.


 

NPM

The Node Package Manager (NPM) allows you to easily manage modules in projects by downloading packages, resolving dependencies, running tests, and installing command-line utilities.

Even though doing so is not essential to the core functionality of the project, you truly need to work efficiently on projects that rely on other pre-existing modules released by third parties.

NPM is a program written in Node.JS and shipped with the binary packages (the MSI Windows installer, and the PKG for the Mac). If you compiled node from the source fles, you want to install NPM as follows:

$ curl http://npmjs.org/install.sh | sh

To ensure successful installation, issue the following command:

$ npm --version

Te NPM version should be displayed.

INSTALLING MODULES

To illustrate the installation of a module with NPM, install the colors library in the directory my-project and then create an index.js fle:

$ mkdir my-project/

$ cd my-project/

$ npm install colors

Verify that the project was installed by ensuring the path node_modules/colors was created.

Then edit index.js with your favorite editor:

$ vim index.js

And add the following contents:

require(‘colors’);

console.log(‘smashing node’.rainbow);

Te result should look like Figure 1-4.


 

DEFINING YOUR OWN MODULE

To defne your own module, you need to create a package.json fle. Defning your own module has three fundamental benefts:

1. Allows you to easily share the dependencies of your application with others, without sending along the node_modules directory. Because npm install takes care of fetching everything, distributing this directory wouldn’t make sense. This is especially important in SCM systems like Git.

2. Allows you to easily track the versions of the modules you depend on that you know work. For example, when you wrote a particular project, you ran npm install colors and that installed colors 0.5.0. A year later, due to API changes, perhaps the latest colors are no longer compatible with your project, and if you were to run npm install without specifying the version, your project would break.

3.Makes redistribution possible. Did your project turn out fne and you want to share it with others? Because you have a package.json, the command npm publish. publishes it to the NPM registry for everyone to install.

In the directory created earlier (my-project), remove the node_modules directory and create a package.json file:

$ rm -r node_modules

$ vim package.json

Then add the following contents:

{

    "name": "my-colors-project"

  , "version": "0.0.1"

  , "dependencies": {

     "colors": "0.5.0"

    }

}

Note: The contents of this fle must be valid JSON. Valid JavaScript is not enough. Tis means that you must make sure, for example, to use double quotes for all strings, including property names.

Te package.json fle is the file that describes your project to both Node.JS and NPM. The only required fields are name and version. Normally, modules have dependencies, which is an object that references other projects by the name and version they defned in their package.json files.

Save the fle, install the local project, and run index.js again:

$ npm install

$ node index   # notice that you don’t need to include “.js”!

In this case, the intention is to create a module for internal use. If you wanted, NPM makes it really easy to publish a module by running:

$ npm publish

To tell Node which file to look for when someone calls require(‘my-colors-project’) we can specify the main property in the package.json

{
    "name": "my-colors-project"
  , "version": "0.0.1"
  , "main": "./index"
  , "dependencies": {
     "colors": "0.5.0"
    }
}

 When you learn how to make modules export APIs, the main property will become a lot more important, because you will need it to define the entry point of your modules (which sometimes are comprised of multiple fles). 

To learn about all the possible properties for the package.json file, run:

$ npm help json

Tip: If you never intend to publish a certain project, add “private”: “true” to your package.json. This prevents accidental publication.

INSTALLING BINARY UTILITIES

Some projects distribute command-line tools that were written in Node. When that’s the case, you need to install them with the -g fag.

For example, the web framework you’re going to learn in this book called express contains an executable utility to create projects.

$ npm install -g express

Then try it out by creating a directory and running “express” inside:

$ mkdir my-site

$ cd mysite

$ express

Tip: If you want to distribute a script like this, include a flag “bin”: “./path/to/script” pointing to your executable script or binary when publishing.

 EXPLORING THE NPM REGISTRY

Once you get comfortable with the Node.JS module system in Chapter 4, you should be able to write programs that leverage any module in the ecosystem.

NPM has a rich registry that contains thousands of modules. Two commands are instrumental in your exploration of the registry: search and view.

If you want to search for plugins related to realtime, for example, you would execute the following:

$ npm search realtime

This will search all the published modules that contain MySQL in their name, tags, and description felds.

Once you find a package that interests you, you can see its package.json and other properties related to the NPM registry by running npm view followed by the module name. 

For example:

$ npm view socket.io

Tip: If you want to learn more about a certain NPM command, type “npm help <command>.” For example, “npm help publish” will teach you more about how to publish modules.

SUMMARY

Afer this chapter, you should now have a working Node.JS + NPM environment.

In addition to being able to run the node and npm commands, you should now have a basic understanding of how to execute simple scripts, but also how to put together modules with dependencies.

You now know that an important keyword in Node.JS is require, which allows for module and API interoperability, and which will be an important subject in Chapter 4, afer quickly reviewing the language basics.

You also are now aware of the NPM registry, which is the gateway to the Node.JS module ecosystem. Node.JS is an open source project, and as a result many of the programs that are written with it are also open source and available for you to reuse, a few keystrokes away.

猜你喜欢

转载自zhebushiren.iteye.com/blog/2044609