node. JS summary-can cope with bat's social recruitment interview

Source: Internet
Author: User
Tags lua install node

What is Nodejs

node. JS uses a modular architecture that defines and uses modules in accordance with the COMMONJS specification. module and file is a one by one correspondence, that is, loading a module, is actually loading a corresponding module file.

JS is a scripting language, and the scripting language requires a parser to run. For JS written in the HTML page, the browser acts as the parser's role. For a js,nodejs that needs to run independently is a parser.

Each parser is a running environment that not only allows JS to define various data structures, perform various calculations, but also allows JS to do something with the built-in objects and methods provided by the running environment. For example, the purpose of JS running in the browser is to manipulate the DOM, and the browser provides the document built-in objects. While the use of JS running in Nodejs is to manipulate disk files or build an HTTP server, Nodejs provides, and so on, the fs http built-in objects.

Node. JS is designed to develop large-scale, high-concurrency network applications, one of the bottlenecks of this network application is the processing efficiency of I/O. Due to the limitations of hardware and network, the speed of I/O is often fixed, how to deal with more customer requests in this premise, and improve the efficiency of CPU usage becomes the biggest problem for the developers. Thanks to the event-driven programming model, node. JS uses a single event loop thread to process customer requests, assigning I/O operations to each asynchronous processing module (which most people don't understand, and node. JS contains many modules that can use JS to call the system's API directly) , not only solves the problem of I/O blocking in single-threaded mode, but also avoids the problem of resource allocation and preemption in multithreaded mode.

  Single thread mode:

The client initiates an I/O request (database query), and then waits for the server side to return the I/O results, returning the results and then manipulating them, but this request often takes a long time (for the CPU processing power of the server). In this process, the server is unable to accept new requests, that is, blocking I/O. This approach, though simple, is not practical, especially when faced with a large number of requests, is simply not available. This kind of scenario is similar to the Train Station ticket window queue to buy tickets, if you during the Spring Festival to the Beijing railway station line bought tickets, will not think this is a good way to deal with. Fortunately, few servers are now taking this approach.

  Multithreaded mode:

In this way, the server assigns a thread to each request, and all tasks are executed within its own thread, much more efficiently, as the station opens several ticket-selling windows. But as the reader has seen, in the Spring Festival during the various ticket window is still overcrowded, why the railway station no longer open more ticket window? Of course because of the cost. The same thread, the server each created a thread, each thread will probably occupy 2M of system memory, and the switch between threads will also reduce the server processing efficiency, based on cost considerations, this processing method also has some limitations. However, this is not the main thing, the main thing is that it is very difficult and error prone to develop multi-threaded software. Programmers need to consider deadlocks, data inconsistencies and other issues, multi-threaded programs are extremely difficult to debug and test. Basically, when the program runs out of error, the programmer knows that his program is wrong. And the cost of such errors is often huge, those who visit the vast number of e-commerce sites are often exposed to price errors and other news that led to loss of the company.


The client initiates an I/O request and passes in a function that is automatically called after the I/O result is returned, and the request does not block subsequent operations. Just like the phone booking, imagine you early in the morning to the office, to the railway station to call, will own ticket information, address to tell each other, and then put down the phone, cup of tea, browse the Web, reply to today's e-mail, you do not have to control the train tickets, if you book a ticket, The railway station will send you a ticket in accordance with the contact information mentioned on your phone. Undoubtedly, this is an extremely ideal way of handling. All requests and simultaneous incoming callback functions are sent to the same thread, which is often called the Event loop thread, which is responsible for returning the result to the callback function after I/O has finished executing. It is important to note that the I/O operation itself is not executed within that thread, so subsequent requests are not blocked. For example: Request A to access the database, request B to access the file system, assuming that the event loop first receives a request, then event Loop will give a callback method to the processing access to the database asynchronous processing module. The event loop can then accept request B and give the callback method of B to a processing module that handles the filesystem. The event loop then continues to wait for the request. When the asynchronous processing module that accesses the data is finished, the callback method of a is called actively. In a callback method, customer A is sent the queried data (which, of course, needs to be done briefly using the event loop).


Why use JavaScript

In fact, at the beginning of the implementation of node. js, the author Ryan Dahl did not choose JavaScript, and he tried C, Lua, because of its lack of some high-level language features, such as closures, functional programming, resulting in complicated procedures, difficult to maintain. JavaScript is a language that supports the functional programming paradigm, which fits well with the node. JS Event-driven programming model. With the V8 engine provided by Google, the JavaScript language is executed much more quickly. The final presentation in front of us becomes node. js, not the implementation of Node.c,node.lua or other languages. JavaScript's anonymous and closure features are ideal for event-driven, asynchronous programming. JavaScript has a good performance in dynamic languages, and developers have performed performance analysis on Javacript, Python, Ruby and other dynamic languages, discovering that JavaScript performance is better than other languages, plus V8 engine is the same kind of leader, So node. JS also benefits from its performance.

node. JS is written in the C + + language and is a JavaScript operating environment. Why use the C + + language? According to the memory of node. JS founder Ryan Dahl, he initially wanted to use Ruby to write node. js, but later found that the performance of the Ruby virtual machine did not meet his requirements, and later he tried to use the V8 engine, so he chose the C + + language.

node. JS uses Google Chrome's V8 engine for good performance while also providing many system-level APIs such as file manipulation, network programming, and more.

node. JS is a back-end JavaScript runtime environment (supported systems include *nux, Windows), which means you can write system-level or server-side JavaScript code and give it to node. js to interpret the execution

Multi-core Processor case

JavaScript in Nodejs is actually executed on a single thread, but as the host's Nodejs itself is not single-threaded, Nodejs in the I/O aspect is also used to assist in the asynchronous implementation of a small number of additional threads. Programmers don't have the opportunity to create threads directly, which is why some students take it for granted that Nodejs's single thread doesn't make good use of multicore CPUs, and they might even say that it's hard to imagine a single-threaded program being developed collaboratively by multiple people.

Nodejs encapsulates an internal asynchronous implementation, which causes the programmer to be unable to manipulate the thread directly, causing all the business logic operations to be dropped on the JavaScript thread, which means that the I/O problem is well resolved at high concurrent requests. But all of the business logic operations are running on JavaScript threads all of the way, creating a crowded JavaScript thread. Nodejs's weaknesses at this time will be exposed, single-threaded operation to form the bottleneck, slowing down the efficiency of I/O. This can be considered a disadvantage of not being able to take advantage of multicore CPUs in dense computing situations. This congested JavaScript thread gives the I/O a performance cap.

But things are not absolute. Back to the front-end browser, in order to solve the thread congestion situation, the Web worker emerged. In the same way, node also provides child_process.fork to create a child process for node. In the case where a node process is able to solve the dense I/O, the rest of the node can be used as a resident service to solve the problem of operation blocking (distributing the operation to multiple node processes, similar to Apache creating multiple child processes). Of course, child_process/web worker mechanism can only solve the problem of single machine, big Web application is impossible to complete all the request service with one server. The advantage of Nodejs on I/O is that it is not a problem to communicate across multiple OS node. The answer to solving Nodejs's computationally intensive problems is also very simple, which is to distribute the operations to multiple CPUs.

In the writing of the article, node's latest release of 0.5.10 added the cluster startup parameters. The parameters are used in the following ways:

Node Cluster server.js

When node is started, when this parameter is attached, node detects the number of CPUs on the machine to determine how many process instances are started, and these instances automatically share the same listening port.


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 and module three predefined variables to use.


requirefunction is used to load and use other modules in the current module, passing in a module name and returning a module export object. The module name can use a relative path ( ./ starting with), or an absolute path (beginning with a letter / or C: the like).


exportsObject is an exported object of the current module that is used to export the module's public methods and properties. When other modules require use the current module through a function, they are the objects of the current module exports .


modulesome information about the current module can be accessed through an object, but the most useful is to replace the exported object of the current module. For example, the module export object is a normal object by default and can be used in the following way if you want to change to a function.

module.exports = function() {    console.log(‘Hello World!‘);};

In the above code, the module default export object is replaced with a function.

Module initialization

The JS code in a module is executed only once when the module is first used, and the exported object of the module is initialized during execution. After that, the cached exported object is reused.

Main module

The module passed to Nodejs by command-line arguments to start the program is called the main module. The main module is responsible for scheduling other modules that compose the entire program to complete the work. For example, when you start a program with the following command, it main.js is the main module.

$ node main.js
Binary modules

Although we generally use JS to write the module, but Nodejs also support the use of C/b + + to write binary modules. The compiled binary modules are .node used in the same way as the JS module except for the file extension. Although the binary module can use all the functions provided by the operating system, it has unlimited potential, but it is too difficult for the front-end students to write, and it is difficult to use across platforms.

Interviewers usually ask: what is node. js? What are the benefits of node. js relative to traditional servers?  Why do you have these benefits? Why choose JS for its development code?

According to the above, when you write a small example, you can basically deal with it. For example: I install node. js on the server, then write a JS code, save, this JS code, need you require HTTP module, then create a new HTTP service, then listen to the port, and then impersonate the HTTP request. At the same time, understand the common modules of node. js, such as: Child_process,url and other modules.

Come on!

node. JS summary-can cope with bat's social recruitment interview

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: 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.