node. JS Getting Started

Source: Internet
Author: User

Console is a console object provided by node. JS that contains operations written to standard output, such as Console.log, Console.error, and so on.

Console.log is the most commonly used output instruction, can accept any parameter, support%d,%s variable reference.

REPL mode

Running the parameterless node will start, and the > Input command appears.

Establishing an HTTP server

Run node filename. js, visit http://127.0.0.1:3000

Call the HTTP module, reply to all HTTP requests for the same content, and listen on Port 3000. The event listener is created in the Listen function, and node. JS does not exit the event loop until CTRL + C is pressed to end.

var http = require (' http '); http.createserver(function(req, res) {    Res.writehead (  {' Content-tyle ': ' text/html '});    Res.write (' );    Res.end (' <p>hello world</p> ');}). Listen(console.log); ("HTTP server is listening at Port 3000");

Synchronous I/O blocking I/O

If a thread encounters disk read-write or network traffic (collectively referred to as I/O operations) during execution, the operating system deprives the thread of CPU control, suspends execution, and gives the resource to other worker threads.

When the I/O operation is complete, the operating system relieves the blocking state of the thread and restores its control over the CPU to continue execution.

var  FS  = require (' FS '); var data = Fs.readfilesync (' file.txt ', ' utf-8 '); console.log (data); Console.log (' end. ') ); // Run Results nimaend.

asynchronous I/O non-blocking I/O

When a thread encounters an I/O operation, it sends an I/O request to the operating system and proceeds to the next statement. When the operating system finishes I/O operations, the thread that notifies the I/O operation as an event is handled by the thread at a particular time. In order to handle asynchronous I/O, threads must have an event loop, constantly checking for unhandled events, and sequentially processing them.

var  FS  = require (' FS '); Fs.readfile (' file.txt ', ' utf-8 ',function(err,data) {    if  (Err) {        console.error (err);     Else {        console.log (data);    }}); Console.log (' end. ') ); // Run Results End.nima

The work knowledge that is done when the fs.readfile is called sends an asynchronous I/O request to the operating system and then immediately returns and executes the following statement, which then enters the event loop listener event. When FS receives an event that the I/O request completes, the event loop actively invokes the callback function to complete the subsequent work.

Not all APIs have synchronous and asynchronous versions, and node. JS does not encourage the use of synchronous I/O.

Event

The event is provided by the Eventemitter object.

var Eventemitter = require (' Events '). Eventemitter; var New Eventemitter (); Event.on (function() {    console.log (' some_event occured. ') );}); SetTimeout (function  () {    event.emit (' some_event '); // output some_event occured after one second.

The event object registers a listener for the events some_event, and the Some_event listener is called when the event some_event is sent to the event object after the SetTimeout 1000 milliseconds.

Modules and Packages

Exports is the interface that the module exposes, and require is used to obtain the interface of a module from the outside, that is, the exports object of the acquired module.

Cover exports

function Hello () {

};

Exports. hello = hello;

In other files you need to go through require ('./filename '). Hello to get the Hello object.

Module.exports = Hello;

The object require ('./filename ') can be obtained directly.

When the module is referenced externally, its interface object is the Hello object itself to be exported, not the original exports.

exportsIsmodule.exportsA reference, just for ease of use. When you want to output a single project such as a constructor, you need to use themodule.exports

You cannot assign a value to a module.exports by assigning a value directly to the exports. Exports is actually just a variable that points to the same object as the Module.exports, which itself is released after the module points to the end, but module does not, and therefore can only be changed by Module.exports to the provider.

Create a Package

when node. JS calls a package, it checks the main field of the Package.json file in the package as the interface module for the package, and if the Package.json field does not exist, it attempts to find Index.js or Index.node as the interface for the package.

NPM

Get a Package

NPM I/install Package_name

The default use of the Install command is local mode, which is placed under the Node_modules subdirectory of the current directory. node. JS's require tries to search the Node_modules subdirectory while loading the module, so packages installed using NPM native mode can be referenced directly.

Global mode

NPM I/install package_name- G

Most of the time it is not because many programs have the potential to use it, but instead of using global schemas to reduce multiple replicas, the local schema does not register the PATH environment variable. NPM Local mode simply installs the package into the Node_modules subdirectory, where the bin directory is not contained in the PATH environment variable and cannot be called directly from the command line. When the global mode is installed, NPM installs the package to the system directory, and the file contained in the Bin field in the Package.json file is linked to the/usr/local/bin/. /usr/local/bin/is defined by default in the PATH environment variable.

Mode Can be used via require Register path
Local mode Is Whether
Global mode Whether Is

We are going to get a package as part of the project runtime through local mode and install it in global mode for use at the command line.

Publish a Package

Use NPM init to generate Package.json based on interactive play

Create Index.js as the interface for the package.

Use NPM AddUser to create your account, and then use NPM whoami to test for your account.

Publish: Run NPM publish in the directory where the Package.json is located, Access http://search.npmjs.org/to find the published package.

Update: Modify version in the Package.json file and re-use the NPM Publish command.

Cancel: NPM unpublish

node. JS Getting Started

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.