node. JS Knowledge Point Detail (i) Basic part

Source: Internet
Author: User
Tags jquery library node inspector

Transferred from: http://segmentfault.com/a/1190000000728401

Module

node. JS provides exports and require two objects, which exports are interfaces exposed by the module, that are require used to obtain an interface for a module externally, that is, the object of the acquired module exports .
Next we'll create hello.js the file with the following code:

function() {  console.log(‘Hello World‘);}

In the example above, hello.js the exports object is world used as the provider of the module, in which the main.js require(‘./hello‘) main.js member functions of the object can be accessed directly by loading the module exports .

requireThe method accepts the following types of parameters:

http、fs、path等,原生模块。./mod或../mod,相对路径的文件模块。/pathtomodule/mod,绝对路径的文件模块。mod,非原生模块的文件模块。

Let's take the example of two methods for calculating the circumference and area of a circle:

var PI = Math.PI;exports.area = function (r) { return PI*r*r;};//exports 是对象,向外提供了area方法接口 exports.circumference = function (r) { return 2*PI*r;};

Save the above as circle.js below by require calling the module:

var circle = require("./circle.js");//require通过引入模块文件,找到exports对象提供的接口console.log("The area of a circle of radius 4 is " + circle.area(4));

Writing a slightly larger program typically blocks the code. In NodeJS , the code is generally reasonably split into different JS files, each file is a module, and the file path is the module name.

When writing each module, there are require、exports、module three pre-defined variables available for use.
The module name can use a relative path ( ./ starting with), or an absolute path (beginning with a C: drive letter such as/or). In addition, the extension in the module name .js can be omitted.

Advantages and disadvantages of modularity:
a>优点:可维护性1.灵活架构,焦点分离2.方便模块间组合、分解3.方便单个模块功能调试、升级4.多人协作互不干扰可测试性1.可分单元测试b>缺点:性能损耗1.系统分层,调用链会很长2.模块间通信,模块间发送消息会很耗性能
node. JS Common Modules and components
 包管理 Package Management: NPM  框架 Framework: ExpressJS  模板 Template: Jade  中间件 Middleware: Connect  WebSocket: Socket.io  Mongo DB (选了个自己喜欢的)  Mongoose (as a MongoDB ORM)  调错 Debugging: Node Inspector  测试 Test: Mocha + should.js  控制无止境的内嵌回调 (Control the Callback flow): Async
What can node. js do? Web development: Express + EJS + mongoose/mysql
express 是轻量灵活的Nodejs Web应用框架,它可以快速地搭建网站。Express框架建立在Nodejs内置的Http模块上,并对Http模块再包装,从而实际Web请求处理的功能。ejs是一个嵌入的Javascript模板引擎,通过编译生成HTML的代码。mongoose 是MongoDB的对象模型工具,通过Mongoose框架,可以进行访问MongoDB的操作。mysql 是连接MySQL数据库的通信API,可以进行访问MySQL的操作。

Typically Node.js , Web development requires 3 frameworks to work with, like SSH in Java.

Web chat Room (IM): Express + Socket.io

socket.ioOne is a NODEJS architecture-based, supported websocket protocol for a software package that communicates at all times. socket.ioprovides a complete package for cross-browser building of real-time applications, socket.io fully javascript implemented.

Web crawler: Cheerio/request

cheeriois a special customization for the server, fast, flexible, packaged jquery core functionality toolkit. Cheerio includes a subset of the jquery core, which removes all DOM inconsistencies and incompatible browser parts from the jquery library, revealing its truly elegant API. Cheerio work on a very simple, consistent DOM model, parsing, manipulating, rendering is incredibly efficient. The base end-to-end benchmark shows that the cheerio is approximately eight times times faster than the Jsdom (8x). The Cheerio encapsulates @fb55-compatible htmlparser and is capable of parsing virtually any HTML and XML document.

Web blog: Hexo

Hexois a simple, lightweight, based on Node a static blog framework. Hexowe can quickly create our own blogs, which can be done with just a few commands.

When you publish, Hexo you can deploy it on your own Node server, or you can deploy it github . For individual users, the deployment is a lot of good github , not only to eliminate the cost of the server, but also reduce the various system operations of the trouble (System management, Backup, network). So, based on github the personal site, is beginning to pop up ....

Front-end package management platform: bower.js

Bower is the twitter introduction of a package management tool, based on nodejs the concept of modularization, the function of scattered into the various modules, the modules and modules exist between the connection, through the Bower to manage the connection between the modules.

Single Thread

javascriptThe language execution environment is single thread.
The so-called "single thread" means that only one task can be completed at a time. If you have multiple tasks, you must queue, complete the previous task, perform the next task, and so on.

The advantage of this model is that the implementation is relatively simple, the execution environment is comparatively pure; the disadvantage is that as long as a task takes a long time, the subsequent tasks must be queued, delaying the execution of the whole program. Common browsers are unresponsive (suspended animation), often because a piece of Javascript code is running for a long time (such as a dead loop), causing the entire page to be stuck in this place, and other tasks cannot be performed.

The bottleneck of most WEB applications is to read and write the I/O disk, read and write the network, read and write the database. How you use the strategy to wait for this time is a key to improving performance

Synchronous vs. asynchronous

To solve this problem, the Javascript language divides the execution pattern of the task into two types: synchronous (synchronous) and asynchronous (asynchronous).

"Synchronous Mode" is the last paragraph of the pattern, after a task to wait for the end of the previous task, and then execute, the execution order of the program is consistent with the order of the tasks, synchronous; "Asynchronous mode" is completely different, each task has one or more callback functions ( callback ), after the end of the previous task, Instead of performing the latter task, the callback function executes, and the latter task executes at the end of the previous task, so the order of execution of the program is inconsistent and asynchronous with the order in which the task is ordered.

The asynchronous pattern is important. On the browser side, a lengthy operation should be performed asynchronously to avoid the browser losing its response, and the best example is the Ajax operation. On the server side, "asynchronous mode" is even the only mode, because the execution environment is single-threaded, and if all requests are allowed to execute synchronously http , the server performance will drop sharply and will soon lose its response.

Processes and Threads

Processes and threads in a Mac system

As we can see, a process can include multiple threads, the process is like the workshop in the project, the thread is the worker of this workshop, in the introduction of the threading operating system, usually the process as the basic unit of allocating resources, and the thread as the basic unit of independent operation and independent Dispatch. Because the thread is smaller than the process, and basically does not have the system resources, the cost of its scheduling will be much smaller, can be more efficient to improve the degree of concurrent execution among the multiple programs within the system.

Difference

The difference between a thread and a process is that the child process and the parent process have different code and data spaces, while multiple threads share the data space, and each thread has its own execution stack and program counter for its execution context. Multithreading is mainly to save CPU time, play use, depending on the situation. The running of a thread requires the use of the computer's memory resources and CPU.

Modules and Package modules

Module: A file that implements some specific functionality for modular programming. Modules are introduced via require (module name).
-Functions in the module, such as variables, functions, are exports provided to the caller using a property assigned to the object.

Modules are reusable code libraries. For example, modules for interacting with databases, modules that support web development, and modules that facilitate communication through web sockets

How do I use modules?

It is very convenient to use modules in node, where JavaScript you can use global functions require() to load a module directly in your code. For example, we can use require("http") to load the node HTTP server module that comes with

A package is a folder that encapsulates modules for publishing, updating, dependency management, and versioning. By package.json describing the package information: the entry file, the dependent external package, and so on. npm installInstall the package by command, and by require using the package.

Package.json

When developing an Node.js application, it's obviously time-consuming to install a single module, or forget to install a module. npmallows developers to use package.json files to specify which modules to use in the application, and to install them through a single command:

npm install

package.jsonThe file contains only project information that is represented in a specific format. One of the smallest package.json files would be this:

{    "name" : "example 1",    "version": "0.0.2", "dependencies":{ "underscore":"~1.2.1" }}

Using package.json files means we don't have to remember which modules the application depends on, and other developers will find it easy to install your application

npm install <name>安装nodejs的依赖包npm install <name> -g  将包安装到全局环境中npm install <name> --save  安装的同时,将信息写入package.json中npm init  会引导你创建一个package.json文件,包括名称、版本、作者这些信息等npm remove <name>移除npm update <name>更新 
Properties of the Package.json
name - 包的名称version - 包的版本description - 包的描述homepage - 包主页author - 包的作者contributors - 贡献者到包的名字dependencies - 依赖关系的列表。NPM自动安装所有在这里的包node_module文件夹中提到的依赖关系。repository - 包的库类型和URLmain - 包的入口点keywords - 关键字npm install module-name -save 自动把模块和版本号添加到dependencies部分npm install module-name -save-dve 自动把模块和版本号添加到devdependencies部分
asynchronous I/O and event-driven

Node.jsThe asynchronous mechanism is event-based and I/O is the meaning of the input and output, referring to the communication between the computer and the person or data processing system. You can I/O think of the movement of data between one input and one output.

Each one I/O is a request, all disks I/O , network traffic, database queries are requested in a non-blocking manner, and the returned results are handled by the event loop. As shown in the following:

Node.jsThe process only processes one event at a time, and immediately enters the event loop to check and handle subsequent events. The advantage of this is that the CPU and memory concentrate on one thing at the same time, while simultaneously executing the time-consuming I/O operations as much as possible

Start Node programming

Here, I recommend that you use webstorm node.js the development, convenient and fast, compared to CMD, or Mac terminal is very useful.

As for the installation of node everyone on their own Baidu bar, here will not repeat, look at webstorm the next node programming interface bar:
We just have to press the right mouse button in the well-written node code interface and then click Run to do it quickly and easily.

The following is the output interface of node:

MacWeb Development under the system, I recommend that you use the three tools are: Coda2 These are currently I have the best development tools, you might want to try which is more in line with their taste.

webstormnode development in the need to configure a certain file, everyone on their own Baidu bar, because I webstorm have been configured, so can not show you the steps, the approximate step is, in the Mac system is the first click on the top bar webstorm , and then click, perference and then click Node.js and NPM , Then click on the Configure configuration on the right, and the end will probably look like this:

windowsThe system and this process step is probably similar ah, I use the version is 8.0.4.

Global variables

In JS programming, we'd better add the var keyword to each variable to avoid polluting the global namespace and increasing the risk of coupling the code.

Console

consoleUsed to output characters to the standard output stream standout (stdout) and standard error stream (stderr).

console.log()Prints a character to the standard output stream and ends with a newline character, which accepts multiple parameters and will output in a C-like printf() format

console.log(__dirname)输出文件目录

Calculate Code Run time

    console.time(label)    console.timeEnd(label)

We just have to give the same tag at the beginning and the end, and put in the middle where you want to calculate the execution time of any code.

__filenameAnd __dirname
    console.log(__filename);// /Users/hwax/Desktop/My Project/avalon/hello.js    console.log(__dirname);// /Users/hwax/Desktop/My Project/avalon__filename:开发期间,该行代码所在的文件。__dirname:开发期间,该行代码所在的目录。
Path.join ([path1],[path2],[...])
合并参数得到一个标准化的路径字符串path.join(‘/foo‘, ‘bar‘, ‘baz/abc‘)// returns‘/foo/bar/baz/abc‘ 
Run the Hello World program

First in the terminal input:

trigkit4:~ trigkit4$ vi index.js

Enter vim after entering i , enter edit mode, and then enter:

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/");

Then press ESC , exit edit mode, enter :w save, and then enter :q exit

Then enter the following command at the terminal:

trigkit4:~ trigkit4$ node index

You can see the terminal output:

Server running at http://127.0.0.1:8124/

Then open the browser, enter the address to see the outputhello world

node. js Package Directory

The Node.js root directory structure of a generic package is as follows:

package.json —— 描述包的json文件 src —— 保存C/C++源文件的文件夹 deps —— 保存包所用到的依赖文件夹 test —— 保存模块测试的文件夹 index.js —— 包的入口文件 "scripts": {//“scripts”是一个由脚本命令组成的hash对象,他们在包不同的生命周期中被执行。key是生命周期事件,value是要运行的命令。        "test": "node ./libuv/test.js" },"main": "index.js",//包的入口文件,如不指定,则为根目录下的index.js

node. JS Knowledge Point Detail (i) Basic part

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.