Node. js Development Guide: basic concepts and development environment Configuration

Source: Internet
Author: User
Tags create index

1 Introduction to node. js

Node. JS is a development platform that enables JavaScript to run on the server. It uses the V8 engine to execute JS scripts and provides JS Interfaces Based on commonjs specifications, which makes code development more portable.

Node programming uses the idea of events to asynchronously process disks, networks, user requests, database requests, and so on, so that the execution efficiency of a single thread is higher. Of course, the disadvantage is that asynchronous execution is not easy to understand program behavior.

2 node installation and configuration

Node has related versions on various platforms. You can download them from the official website and install them as instructed.

After node is installed, an NPM module is provided by default to manage third-party extension packages, similar to PhP pear. Its basic commands are similar to Yum, such as NPM install package.

The node installation package has two installation modes: global module and local mode. The former installs the third-party extension package in the OS system path so that related tools can be found in the command line environment. The latter installs the third-party package in node_modules under the command execution directory as a dependency for a project, without exporting it to the global environment.

3 node Quick Start

3.1 run Node

The basic method for running a node application is to first write a JS file and then run it with node.

Node also supports direct execution of JS Code as its parameter, such as node-e 'console. Log ('Hello world )'

Similar to pyhon, node provides the repl mode. You can run node directly on the command line. In repl mode, node can be input and executed row by row.

With NPM, you can install a tool named supervisor to the global environment. Instead of using node to execute JS scripts, You can automatically restart the node instance after modifying the JS file.

Node comes with an HTTP module, so node can complete functions similar to PhP, but does not need front-end web support. The following example shows a simple web server.

var http = require('http');http.createServer(function (request, response) {  response.writeHead(200, {'Content-Type': 'text/plain'});  response.end('Hello World\n');}).listen(80);console.log('Server running at http://127.0.0.1:80/');

Module and package 3.2

In node, the module corresponds to the file. A larger package can be a directory, which consists of multiple modules. Node provides the required function to load modules and packages.

To better understand the modules and packages, it is best to create a module and package by yourself.

3.2.1 create a module

Creating a module is simple. You only need to create a new JS file to implement the corresponding functions, and finally put the interface to be exported into the exports object. Example:

//module hello.jsvar something;exports.sayHello = function(){  console.log('hello');}//var h = require('./hello.js')//h.sayHell();

Exports is the export interface object of the module. The Node module load function require () analyzes and exports the exports object of the loaded module.

In the current module, the module object references the current module. Therefore, module. Exports and exports point to the reference of the same object. In some cases, you can overwrite the exports object to be exported in order to get the export object quickly. Example:

//file hello.jsvar hello = function(){  console.log('hello');};module.exports=hello;//require('hello.js')();

3.2.2 module searching and Loading Mechanism

The node's require function stores the loaded modules in require. cache by file name. Therefore, although the modules are loaded multiple times, only the same module instance is returned. Cache information can be printed in the repl console function under Node debug.

Node modules are divided into core modules and file modules.

The core module is the module declared in node API. It has the highest priority during loading, that is, if there is a module with its duplicate name, only the core module is loaded.

The file module is a module that stores individual files or directories. The file module can be loaded in two ways: an absolute or relative path. In this case, the node searches for and loads the file by path. If the file module cannot be found, an exception is thrown. If the module is neither a core module nor a path-based load, node searches for the node_modules directory in the current directory to find the corresponding module. If no result exists, search for node_modules in the parent directory and repeat the process until the root directory.

3.2.3 create a package

The package in node is a directory. The commonjs specification has strict requirements on packages, such as the definition of package. JSON. The directory contains bin/lib/doc/test. Node only requires that the package. JSON file exists in the root directory. The simplest package is to create index. js in a directory and implement the function in index. js. When a node loads a package, it will have a package according to the root directory. JSON. Search for the value of main in the file as the module entry. If the main field does not exist or the corresponding file is not found, search for index. JS as the entry.

After creating the package, you can use the require directory name to include the corresponding package.

3.2.4 release package

If you want to publish your package to the Internet, you can use the NPM tool:

NPM init generates package. JSON in interactive mode

NPM adduser generates users on the node repo website through interaction

NPM publish can publish the package. If necessary, update the version number in package. JSON and re-publish.

NPM unpublish can unpack

3.3 debugging

3.3.1 node debug 

Node debug script. js can be debugged under the command line.

It supports the following commands:

Breakpoint command: Sb (line) Sb ('func') CB ()

Step-by-Step command: Next cont step out

View information: Bt list (n) Watch/unwatch (expr) repl

Execution control: Run restart kill

3.3.2 enable remote debugging

Node -- debug-BRK = 8080 script open the scheduling Server Based on port 8080, and pause the execution and wait for client connection

Use node debug IP: 8080 remotely

3.3.2 Auxiliary Tools

Third-party tools can be used to connect to the debug server more friendly, such as node-inspector. After NPM is installed, it is started and located in the browser.

Http: // ip: Port/debug? Port = debug-Port

References:

1 node. js Development Guide

2 node. js API: http://nodejs.org/api/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.