Nodejs's third day of study

Source: Internet
Author: User

First, CommonJS Specification

The relationship between 1.1nodejs and Commonjs:

1) Nodejs is a server language.

A) ability to open services

b) Ability to read and write files

Server: It is a service software installed

2) Commonjs is the norm of Nodejs.

The meaning of the 1.2COMMONJS specification:

Since Nodejs is written in JavaScript, JavaScript adheres to the ECMAScript specification, and ECMAScript this specification (if it is a specification for a background language) is incomplete, Because its content is only a specification of javascript: lexical, type, expression, method, object and other basic elements.

There are several drawbacks to using ECMAScript as the specification:

1) No module system (not easy to expand)

2) Fewer standard libraries, no standard API for common requirements such as file system, I/O flow, etc.

COMMONJS Specification:

1) have the ability to open the server

2) can do something that the server can do: binary, character encoding, IO read/write ...

3) Nodejs Modular Rules: Reference file require exposed interface: exports,module.exports definition Module

Second, the core module

2.1 Core Module Path

Role:

basename (path) Gets the file name of the incoming path

DirName (path) Gets the incoming path directory

Extname (path) Gets the extension of the incoming path

Join () joins two or more than two paths together

Parse (path) converts the passed-in path to a path object

Format (pathobject) converts a Path object to a string

Delimiter get the operating system delimiter

Isabsolute (path) determines whether a path is an absolute path

Normalize (path) converts a non-standard path to a standard path

Relative (from path to path) a form path to the lookup process to the to path

Sep gets the ' \ ' delimiter under the win system and gets the '/' delimiter under other systems

A collection of POSIX all path methods

2.2 Core Module URL

Role: For manipulating URLs

1.2.1 URL Composition: protocol name, user name and password, server IP address, port number, request path, parameters, hash number

1.2.2 Common APIs:

Url.prase (PATH)

Url.format (Pathobject)

2.3 Core Module QueryString

Action: Parameters in the action URL

2.3.1 QueryString commonly used APIs:

Querystring.parse () convert a parameter string to an object

Querystring.stringify () Convert an object to a string

Querystring.escape (URL) transcode the characters in the URL

Querystring.unescape (URL) converts the transcoded characters in the URL into Chinese characters

Third, the file module

3.1 What is a file module:

Nodejs in the core module, the function of the module is limited, we write a module according to our own needs, this module is collectively referred to as the file module in Nodejs, also called the user module, third Party Package

3.2 How to develop a file module yourself

Process:

One version :

Directly develop a JS file, develop the necessary computing function, use another JS file to reference, but if in the future to join other functions, but also need to add another file, the development of the corresponding function, again with the use of the JS file to reference, too troublesome, in order to make the structure of the code more clear, We've agreed to put all the files in the same folder Node_modules

Note the point:

1) Nodejs is the definition module does not need the keyword define, the other is the same as the modularization in JS

2) Reference file module can be no suffix in the path

Two versions:

Put all the file modules in one Node_modules folder (Note: This Node_module folder is very important, all the file modules in the future development process are placed under this file). However, if in the future we develop content is not limited to a computational function, there may be other features, such as login registration function, then a node_modules below the file is equivalent to two types of files, in order to separate the two types of file. We set up a separate folder for each type of function to manage the corresponding modules, and for each folder in each of the settings of a file (such as a file in Nodejs we call it a package, a package is a number of JS files or JS module composed of, and has a unified export file, And the export file is generally defined as Index.js) (illustrated).

Three versions:

After writing the package if you want to use also direct to the export of the package, so the transformation of the export file generally the path is very long, in order to operate conveniently. We will not go to the full path, but will directly refer to the require above the package name to import the package, although the path is not complete, but after the run to find the file is normal, the nodejs in the execution of require (' package name ') has its own process.

3.3 Nodejs the process of introducing the package

Step one: When Nodejs executes to require (' package name '), the package name is identified as the core module first

Step two: But found that this package is not the core module, will automatically go to the Node_modules file to find the file name of the folder of the package name

Step 2.5: If you find this package, and there is a file called Package.json in the package, Nodejs will find the corresponding entry file according to the main property in Package.json

Step three: If there is no Package.json file, go directly to the package to find a module called Index.js, and load it out

Step four: If not found, the error

3.4 package.js file

Role: Set some important parameters for the current package

generate Package.js File: key directive NPM init-y

Open cmd under the Package folder, enter the instructions above, will automatically generate a Package.json file under this directory

File contents:

{

"Name": "JS",

"Version": "1.0.0",

"description": "",

"Main": "Abc.js",

"Scripts": {

"Test": "Echo \" Error:no test specified\ "&& exit 1"

},

"keywords": [],

"Author": "",

"License": "ISC"

}

function of the property :

Name: Set the names of the current packages (names that will be published on NPM)

Here are some of the official recommendations:

Do not include "JS" and "Node" in the name because the default NPM package is the node. JS program, but you can specify it through the engines field.

The name will be used as part of the URL, all generic naming conventions that conform to the HTTP URL, cannot contain URL illegal characters, and cannot begin with. And _.

The name will also be used as a parameter to the Require () command, so be as concise as possible.

If the package is to be published on the NPM platform, it is best to check for duplicate names and only lowercase letters.

Version: Set the current package versions, for example: v2.0.0

Name and version are the most important of the two fields in Package.json and are the only ones published on the NPM platform, which cannot be published and downloaded if the two fields are not set correctly.

Description: Sets the description information for the current package (for future users to be able to name a search on NPM on a published package)

Main: Set export file for current package

Script: This setting enables the current package to invoke NPM Some command scripts, encapsulating some features

Keywords: Sets the keyword for the current package (for future users to be able to name a search on NPM on a published package)

Author: Author of the current package

License: Set the license certificate version for the current package (BSD-3-CLAUSE,MIT,ISC)

These licenses set out some of the things that other people in the future might be able to do later: using, modifying, forwarding, and using part of the project for sale.

Note: Each package must have a JSON file

3.5 Package

What is a package:

is to put a set of similar file modules into a single folder, and set up a unified export file for all the file modules, such folders are called Packages in Nodejs.

A package that conforms to the COMMONJS specification should be the following structure:

A Package.json file should exist in the top-level directory of the package (must)

The binaries should be included in the bin directory (not required).

The JavaScript code should be included in the Lib directory (must).

The document should be in the Doc directory (not required).

The unit test should be in the test directory (not required).

Use the instructions in the readme.md file, this file must be placed in the top-level directory of the package (must)

Structure:

_ Package Name

|

|__package.json

|

|__bin

| |

| |__ binary files

| |

|__lib

| |

| |__javascript Code

|

|__doc

| |

| |__ Documentation

|

|__text

| |

| |__ Unit Test

|

|__readme.md

3.6 installing and uploading packages via NPM

1) Upload:

Steps:

1) Create a package for the good one standard structure (note: Be sure to meet the requirements of the package), and set some parameters in the Package.json file.

2) go to Npmjs to register an account (: Jhon_j. Click on the image will pop-up drop-down box, select Profile, will open the history of the record release package)

3) Open cmd under the folder you want to publish, and execute the release instructions:

A) NPM AddUser: Follow the boot, enter the user name, password, and register the mailbox.

If you see: Logged in as Jhon_j on https://registry.npmjs.org/. Description Login Successful

b) NPM Publish: see + [email protected] instruction description has been uploaded successfully

2) Revocation:

3) Installation:

A. Local Installation

directive: Local Path of NPM install package

Role: Resolve a package that cannot be posted to the Internet by using this directive on its own inside the company

B. Networked installation

directive: NPM Install package name

I. Installation of this project:

NPM Install package Name

II. Global Package Installation:

NPM Install package name-G

Tip: Since NPM is a foreign site, it may be slower to install. Workaround one: Download a NRM, via NRM to move NPM login from abroad to domestic, using the NRM use CNPM Directive solution Two: Install a CNPM tool, directly through the CNPM to install

Generally which packages are to be installed globally, which packages are to be installed in the readme.md of NPM, the installation of the global package essentially places the files under the directory of the currently used Nodejs

Summary: In the entire NODEJS environment (no matter what the project) you want to use this package, you need to install a global package, but if only this project to use, install a package of this project

3.7 npm Other common Directives

NPM AddUser: The user name, password, and registered mailbox will be booted (if the login succeeds it will show: logged in as Jhon_j on https://registry.npmjs.org/.)

NPM Publish: Release package

NPM Uppublish Package Name @ VERSION number: Revoke a package that has already been released

NPM Install <name> installation Nodejs Dependency Pack

For example, NPM install Express installs the latest version of Express by default, or you can install the specified version by adding the version number later, such as NPM install [email protected]

NPM Install <name>-G packages are installed in the global environment

But in the code, the direct way through require () is that there is no way to call a globally installed package. The global installation is for the command line, as if the Vmarket is installed globally, you can run the VM command directly on the command line

NPM install <name>--save to write information to Package.json

If you have a Package.json file in the project path, you can use the NPM install method directly to install all the dependent packages based on the dependencies configuration

When this code is submitted to GitHub, it is not necessary to commit the Node_modules folder.

NPM init will guide you through the creation of a Package.json file, including name, version, author information, etc.

NPM Remove <name> Remove

NPM Update <name> Update

NPM LS Lists all the packages that are currently installed

NPM root View the installation path for the current package

NPM root-g View the installation path for a global package

NPM help helps, if you want to view the help of the install command separately, you can use the NPM helper install

3.8 require Summary of loading rules

1) require both the core module and the file module are first loaded from the cache (can resolve a file multiple references a file module and repeatedly loaded problem)

2) load a file module in window to use./or. /start (if no suffix is added, Nodejs will function as core module or package to parse)

3) in Mac and Linux with/loading is a file module that loads an absolute path, while under Window/indicates the drive letter of the directory where the current require function is located (for example: C drive, no meaning)

4) A file module can not write the extension, require () will automatically follow the order of. js. node. JSON and then load, if the three extension is not, then as a directory or package to load. If none of the directories or packages are available, an error occurs.

So if you don't add a suffix, in the future if a file returns JSON, it will load slower.

5) Load a package

-Follow the path in the module.paths array to load the incoming package name, if any, to load the industry; if not, the error

-After the Paukka is loaded, if there is a Package.json file, go to the export file where the main attribute corresponds.

-If not, find the default file Index.js

3.9 Debug Nodejs

1) use Console.log ()

Use trouble, use later also want to delete

2) Nodejs with self-debugger

-node Debug A.js

Without any effect, a toy that someday can become powerful

3) Debug with visual Stdio:

Steps:

A) Install Vscode and open the folder that contains the files you want to debug by Vscode

b) Click F5, select Nodejs Open mode, this time Vscode will open a Lanuch.json, modify the "program" attribute, change to "${workspaceroot}/file name. js",

c) You can view the five global objects of a file and add the values of variables in the monitoring file

4) Debug with Webstorm

Nodejs's third day of study

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.