Document directory
What is node JS?
From: Michael abernethy, what is node. js?
What is the purpose of node?
The goal publicly stated by node is "to provide a simple method for building scalable network programs ". What is the problem with the current server program? The bottleneck in the entire web application architecture (including traffic, processor speed, and memory speed) is the maximum number of concurrent connections that the server can process.
Node can solve this problem by changing the connection method to the server. Each connection emits an event running in the node engine process, instead of generating a new OS thread for each connection (and allocating some supporting memory ). Node claims that it will never be deadlocked because it does not allow the use of locks at all, and it will not directly block I/O calls. Node also claims that its server can support tens of thousands of concurrent connections.
How does node work?
Node itself runs V8 JavaScript. JavaScript on the server.
V8 JavaScript engine is the underlying JavaScript engine Google uses for its Chrome browser. Few people think about what JavaScript actually does on the client? In fact, the JavaScript engine is responsible for interpreting and executing code. Google uses V8 to create an ultra-fast interpreter written in C ++, which has another unique feature. You can download the engine and embed itAnyApplication. The V8 JavaScript engine is not limited to running in a browser. Therefore, node will actually use the V8 JavaScript Engine compiled by Google and rebuild it to be used on the server.
Event-driven programming
The education given to many programmers makes them think that object-oriented programming is a perfect programming design, which makes them dismissive of other programming methods. Node uses a so-called event-driven programming model.
Listing 1. event-driven programming using jquery on the client
// jQuery code on the client-side showing how Event-Driven programming works
// When a button is pressed, an Event occurs - deal with it
// directly right here in an anonymous function, where all the
// necessary variables are present and can be referenced directly
$("#myButton").click(function(){
if ($("#myTextField").val() != $(this).val())
alert("Field must match button text");
});
In fact, there is no difference between the server and the client. Yes, there is no button to click or type in the text field, but at a higher level, the eventIsOccurred. A connection is established. This is an event! Data is received through a connection. This is also an event! Data is stopped by connection. This is still an event!
Why is this setting type ideal for node? Javascript is a great event-driven programming language because it allows anonymous functions and closures. More importantly, anyone who has written code is familiar with its syntax.The callback function called when an event occurs can be written at the capture event.. This makes the code easy to write and maintain without complicated object-oriented frameworks, interfaces, and the possibility of over-design. You only need to listen to the event and write a callback function. Other tasks can be handled by the system!
What is its benefit?
As you have seen before, node is very suitable for the following situations: before responding to the client, you may expect high traffic, but the server logic and processing required are not necessarily great. Typical examples of outstanding node performance include:
- Restful API
The Web service that provides restful APIs receives several parameters, parses them, combines a response, and returns a response (usually less text) to the user. This is ideal for node because you can build it to process tens of thousands of connections. It still does not require a lot of logic; in essence, it simply finds some values in a database and forms a response. Because the response is a small amount of text, the inbound request is also a small amount of text, so the traffic is not high, a machine can even handle the API requirements of the busiest companies.
- Twitter queue
Imagine a company like Twitter that must receive tweets and write it into the database. In fact, there are almost thousands of Tweets per second, and the database cannot process the number of writes required during peak hours in a timely manner. Node becomes an important part of the solution to this problem. As you can see, node can process tens of thousands of inbound tweets. It can quickly and easily write them into a memory queuing mechanism (such as memcached) from where another independent process can write them into the database. Node's role here is to quickly collect tweet and pass this information to another write process. Imagine another design (the regular PHP server will try to write data to the database itself): Each tweet will cause a short delay when writing data to the database, because the database call is blocking the channel. Due to database latency, a machine designed in this way can only process 2000 inbound Tweets per second. 1 million servers are required to process 500 Tweets per second. On the contrary, node can process each connection without blocking the channel, so as to capture as many tweets as possible. Only 20 servers are required for a node machine that can process 50,000 tweets.
- Video Game statistics
If you have played the Call of Duty game online, When you view the Game statistics, you will immediately become aware of the problem: to generate statistics at that level, you must track massive amounts of information. In this way, if millions of gamers play games online at the same time and they are in different positions in the game, a massive amount of information will soon be generated. Node is a good solution for this scenario, because it can collect game-generated data, merge the data at least, and then queue the data to write them into the database. It looks silly to use the entire server to track how many bullets a player has fired in the game. If you use a server like Apache, there may be some useful restrictions; but on the contrary, if you use a server to track all the statistics of a game, just as the server running node does, it seems wise.
Node Package Module
One feature of node is the node package module, which is a built-in function for installing and managing node modules. It automatically processes dependencies, so you can be sure that any module you want to install will be correctly installed and contain necessary dependencies. It also supports publishing your own modules to the node community, if you choose to join the Community and write your own modules. You can think of NPM as a method that allows you to easily expand the node function without worrying about this will damage your node installation. Similarly, if you choose to study node in depth, NPM will be an important part of your node solution.
Conclusion
Node is a program that can complete all the tasks that Apache can accomplish (using some modules), and serves as an extensible JavaScript platform that can be built on it as the basis, node can complete more tasks.
Node achieves its goal of providing highly scalable servers. It uses Google's extremely fast JavaScript Engine, V8. It uses an event-driven design to keep the code minimal and easy to read. All of these factors contribute to the ideal goal of node, that is, it is easier to write a highly scalable solution.
Learning
- The node. js homepage is the entry point for understanding this application.
- Download node. js here. You will also need python.
- Browse the node. js API page. Note that the syntax for different releases may be different. Therefore, carefully check the version you have downloaded and the API you are browsing.
- See the node module page, which lists all modules that can be used in node.
- Search for NPM to easily expand the features installed by your node.
Part 2 use node. js for server-side JavaScript programming
Author: Cheng Fu (actually a Hunan fellow Beijing-Shaoshan-Beijing, mark a, http://www.cheng-fu.com)
Modular structure
Node. js uses the module system defined by commonjs. Different functional components are divided into different modules. Applications can choose to use appropriate modules based on their own needs. Each module exposes some common methods or attributes. The module user can directly use these methods or attributes without the implementation details inside the module. In addition to multiple modules preset by the system, the application development team can also use this mechanism to split the application into multiple modules to improve code reusability.
Modules
Using a module in node. JS is very simple. Before using a module, you must first declare its dependencies. You can directly use global functions in JavaScript code.require()To load a module. For examplerequire("http")Can load system presethttpModule. Whilerequire("./myModule.js")Used to loadmyModule.jsModule. If you userequire()If the path starts with "/", it is considered to be the absolute path of the module Javascript file on the operating system. If not, node. js will trynode_modulesDirectory. For example, directory/usr/home/my.jsCalledrequire("other.js")Then, node. js tries to find the following files in sequence:/usr/home/node_modules/other.js,/usr/node_modules/other.jsAnd/node_modules/other.js.
require()The return value of a method is the public JavaScript Object exposed by this module, which contains available methods and attributes. Code List 2 shows the basic usage of the module.
List 2. Basic usage of modules
var greetings = require("./greetings.js");
var msg = greetings.sayHello("Alex", "zh_CN");
process.stdout.write(msg);
As shown in code list 2require()The Return Value of the method is assigned to a variable, which can be directly used in JavaScript code.greetings.jsThe module exposessayHello()Method. The current JavaScript code directly uses this method.
Event-driven
Those who have developed web applications are familiar with the event processing mechanism in the browser. When you are interested in a certain event on a DOM element, you only need to register an event listener on the DOM element. For exampleele.addEventListener("click", function() {})A pair is added.clickEvent listener. When an event occurs, the JavaScript method of the event listener is called. The event processing method is asynchronous. This asynchronous execution method is very suitable for developing high-performance concurrent network applications. In fact, the current high-performance concurrent application development generally has two ways: the first is to use a multi-threaded mechanism, and the other is to use an event-driven approach. The problem of multithreading lies in the difficulty of application development and the possibility of thread hunger or deadlocks, which puts forward higher requirements for developers. The event-driven approach is more flexible and easy to understand and use by web developers, and there are no issues such as thread deadlocks. Relying on the powerful Google V8 engine and Advanced event I/O architecture, node. js can become a good foundation for creating high-performance server-side applications.
The development of applications based on node. js has similar programming models with the development of Web applications. Many modules expose some events and use the code of these modules to add corresponding processing logic by registering the event listener. Code list 4 provides a simple HTTP Proxy server implementation code.
Listing 4. HTTP Proxy Server
Var http = require("http");
Var url = require("url");
http.createServer(function (req, res) {
Var urlObj = url.parse(req.url, true); // Get the proxy URL
Var urlToProxy = urlObj.query.url;
If (!urlToProxy) {
res.statusCode = 400;
Res.end("URL is required.");
}
Else {
Console.log("Processing proxy request:" + urlToProxy);
Var parsedUrl = url.parse(urlToProxy);
Var opt = {
Host : parsedUrl.hostname,
Port : parsedUrl.port || 80,
Path : (parsedUrl.pathname || "") + (parsedUrl.search || "")
+ (parsedUrl.hash || "")
};
Http.get(opt, function(pres) { // request the content of the proxy URL
res.statusCode = pres.statusCode;
Var headers = pres.headers;
For (var key in headers) {
res.setHeader(key, headers[key]);
}
Pres.on("data", function(chunk) {
Res.write(chunk); // write back the data
});
Pres.on("end", function() {
Res.end();
});
});
}
}).listen(8088, "127.0.0.1");
Console.log ("Proxy server has been started on port 8088.");
The implementation of the entire proxy server is relatively simple. First passhttpModulecreateServer()Method To create an HTTP server, and thenlisten()The HTTP server can listen on a specific port. IncreateServer()The parameter passed in is the response method of the HTTP request. In fact, each HTTP request corresponds torequestEvent. The HTTP server creation part in code list 4 is actually equivalent to the implementation method given in code list 5.
Listing 5. How to create an HTTP server using the event mechanism
var server = http.createServer();
server.on("request", function(req, res) {
});
In the request processing methodhttp.get()To obtain the content of the proxy URL. Event-based processing is also adopted here.pres.on("data", function(chunk) {})InpresOfdataA processing method is added to the event. The function of this method is to return the obtained content to the response of the original HTTP request when the content of the proxy URL is obtained. ForendEvent processing is the same. When using node. js for development, you will often encounter such scenarios that use event processing methods and callback methods.
Part 3: Modern JavaScript features (compared with Java, groovy, and Ruby)
Andrew Glover, writer and developer, beacon50 Java Development 2.0: javascript for Java developers
Java developers have never been optimistic about JavaScript, because it seems too lightweight to program with it, and it seems too cumbersome as a script. But some people are still using JavaScript, because it is the foundation of excellent web technologies such as GWT and node. js. In this issueJava Development 2.0Andrew Glover explains why Javascript is an important tool for modern Java developers. Then we introduce the syntaxes required to build the current top-notch Web applications, including JavaScript variables, types, functions, and classes.
Use javascript: F12 in chrome
I like chrome's beautiful JavaScript console. Like Ruby's IRB or Python's shell, chrome provides an interactive environment for browsing JavaScript without web pages.
Note: a better way to debug the following program list is to use the node command line tool provided by node. js. CMD> node
Javascript Variables
Javascript is a relatively easy-to-use language that can tolerate many programming errors and still be executed on loaded web pages. Javascript elements often fail without any prompts. This is mostly good news. If the Javascript language rashly prohibits page loading, the early Web will be messy. That is to say, when we use JavaScript to do what we like to do (for example, asynchronously update the page status), the hasty use of JavaScript will pay the price. For this reason, Java developers should take the time to really understand specific aspects of JavaScript syntax.
Javascript variable processing is very important for understanding. For example, you want to define a variablefoo, Can be directly defined or throughvarDeclaration, as shown in Listing 1:
Listing 1. Variable foo
foo = 'foo'var bar = 'bar'
In list 1fooIs a valid variable in JavaScript. But it lacksvarDeclaration. This is a global variable. ThereforevarA defined variable has a range (for example, in a function that defines it ).
Generally, global variables are troublesome. They can easily cause chaos in variable usage, because global variables can be accessed and changed anywhere in Javascript applications, which leads to potential bugs. Therefore, when programming in Javascript, do not forget to apply the variablevar.
Element and Object
Although Javascript is not perfect, it is very simple in terms of type. In fact, JavaScript only has four basic types, three of which are elements. The primitive type of JavaScript isNumber,String, AndBoolean. You can use JavaScripttypeofOperator to view these types in the operation.
Let's take a look at the problem. In Chrome's JavaScript, enter the content in Listing 2:
Listing 2. Activating types
var string = "test"typeof string
The console output value is"string". Note that the semicolon is optional in JavaScript. As in popular languages,stringQuotation marks are used to define the number. Therefore, numbers are used to define the number. Booleans pass valueTrueOrFalseThere is no semicolon.
Listing 3. Javascript truth and numbers
var aNumber = 10
var anotherNumber = 0.99
var aBool = true
var notABoolean = "false"
You will notice that JavaScript does not distinguish between numeric types; numbers are numbers, but they have different formats.
Javascript also supports common objects, which have instance types, suchArray, As shown in Listing 4:
Listing 4. array instances
> var myArray = ["Hello", 1, true]
> typeof myArray
"object"
> myArray instanceof Array
true
In JavaScriptArrayS is more like a list in other languages: you do not have to limit the size of the List to create, you can save any input content. For example, in Ruby or groovy, JavaScriptArrayS can be created through text Syntax:[]. More importantly, like other languages that support the listArrayS supported methods (as shown in listing 5 ):
Listing 5. Array Method
> var myArray = ["Hello", 1, true]
> myArray[0]
"Hello"
> myArray.length
3
> myArray.pop()
true
> myArray
["Hello", 1]
> myArray.pop()
1
> myArray
["Hello"]
> myArray.push("pushed")
2
> myArray
["Hello", "pushed"]
AvailableArrayTo obtain the value, starting from scratch.ArrayS supportpushAndpopOperation, wherepushAdd a project (in its last position) andpopRemove a project (like a stack, starting from the last one ).
ArrayS also supports iteration, as shown in Listing 6:
Listing 6. Iteration through array
> var myArray = [1,2]
> for(var i = 0; i < myArray.length; i++) { console.log(myArray[i]) }
1
2
Type mandatory
Javascript is not only a weak type of language-it is better than Ruby or groovyWeaker! Javascript can force variables to be of any type at a specific position in the code. This is in line with JavaScript's original idea: web page interaction. Javascript should not rashly prohibit users from reading online articles!
The type is not limited to Javascript, but Javascript is very flexible. Whether this is a good thing or a bad thing depends on what you think. Javascript loose may hide defects, just like global variables.
For example, defineArrayThen, I accidentally tried to perform some numeric operations, or even someStringCascade, as shown in listing 7:
Listing 7. Javascript type flexibility
> var myArray = [1,2]
> console.log(2 * myArray)
> console.log("A" + myArray)
In this example, the first log message is printed.NaNAnd the second one will printA1,2. In the two examples, the code can "run normally", because no error occurs-JavaScript just keeps running. This is a weak type in extreme cases. The same Code in ruby won't run like this, as shown in listing 8:
Listing 8. Ruby does not use that method
> array = ["A", "B"]> ans = 2 * array
The ruby code in listing 8 will go wrong:
TypeError: Arraycan't be coerced into Fixnum
If you tryarrayAdd"A"In the following example:
TypeError: can't convertArray into String
If you try the same operation in groovy, the following results will be obtained:
groovy.lang.MissingMethodException: No signature of method:
java.lang.Integer.plus() is applicable for argument types: (java.util.ArrayList) values:
[[A, B]]
Therefore, you can see the weak types at different layers in the operation. Obviously, JavaScript will be the weakest of measurement types if there is a standard of strength and weakness!
JavaScript Functions
JavaScript Functions, similar to Java methods, are structures used to define and encapsulate reusable behaviors. Functions in Javascript look like groovy closures. Functions in JavaScript are objects. In fact, they are the first type of objects,UnlikeMethods in Java code. Because JavaScript Functions are objects, they can be passed to other functions and called.
ExploitationfunctionKeyword to define the function. Just like the method declaration in Java, you can specify parameters and return some content from JavaScript Functions. Different from dynamic languages, such as groovy or Ruby, the return call is optional (so that the last line of any method will be returned). If you want to get the return value, the return statement must be used in JavaScript Functions; otherwise, no return value will be returned.
You can call a function in Javascript just like calling a closure in groovy. In listing 9, a simple function without parameters is defined. The purpose is to print "blah" on Chrome's JavaScript console ".
Listing 9. Defining and calling functions in Javascript
> function blah() { console.log("blah"); }
> blah() //prints blah
> blah.call() //prints blah
> blah.apply() //prints blah
MethodcallOr MethodapplyThere are brackets for direct calls (that is(). The first class function object is shown here. Listing 10 showsblahWhen the garbage method is called in:
Listing 10. Using functions as objects in Javascript
> blah.foo()
In this example, the error message descriptionfooIt is not a defined method, like this:
TypeError: Object function blah() { console.log("blah"); } has no method 'foo'
Read the error message again. SeefooNoDefined, Which means that if itQuiltDefinition, everything will be normal.
Classes in Javascript
We have discussed the JavaScript support primitives. It also supports objects, suchArray. JavaScript does not support classes-at least not supported in the classic Java language. Because Javascript is a prototype-based language, you cannot define classes.CloneReuse behavior with existing objects. Therefore, in Javascript, class objects are not defined, but defined in functions, and then nested functions are used to define behavior-some of which have been seen during running.
To simulate a class, you must define a function. You can give it a name (that is, a class name), specify parameters (the same as in the constructor), or even use keywords..thisThis means that variables are referenced within the function range. What's more, internal functions can have aliases, which look like method calls.
In listing 11, I will createMessagePrototype (also called a class), which is very simple. I will provide some parameters (where the message comes from, who it sends, and the message itself), and the class will present the message in JSON format.
Listing 11. Functions in Javascript act as classes
function Message(to, from, msg){
this.to = to;
this.from = from;
this.msg = msg;
this.asJSON = function(){
return "{'to':'" + this.to + "', 'from':'" + this.from + "', 'message':'" +
this.msg + "'}";
}
}
In listing 11, I definedMessageFunction-an object with a name and several attributes; that is,to,from, Andmsg. Then I defined an attribute (asJSON) Points to the internal function. Its task is to represent the JSON message in a string.
Note: You can also define the "class" on the web page, use chrome to load, open the Javascript console, and use it interactively. This is what is described in listing 12:
Listing 12. Using classes in Javascript
> var message = new Message('Andy', 'Joe', 'Party tonight!');
> message.asJSON();
"{'to':'Andy', 'from':'Joe', 'message':'Party tonight!'}"
This code is similar to groovy code, or even Java code (if you do not considervar), Isn't it? In fact, we can fully use OOP technology to construct JavaScript applications (that is, the program contains objects with data and interactive methods ).
Conclusion
I hope this article will overturn the obsolete useless JavaScript language theory. In fact, it is very powerful and has a lot of syntactic sugar and can be as convenient as new languages like groovy and Ruby. Some of the features that made JavaScript popular in 1990s are also desirable today.
Given the increasing importance of web for Java application development and the unique position of JavaScript as a browser compatible language, every Java programmer should be familiar with JavaScript. Browsers, whether on computers or on mobile devices, phones, or tablets, are increasingly used to interact with applications. Javascript is the most common medium in all server languages. In addition, understanding JavaScript will make you an excellent programmer in any language field (including the language you are most familiar.
Additional reading:
Javascript development kit http://www.ibm.com/developerworks/cn/web/lp/jstoolkit/
Part 4: coffeescript
From: http://article.yeeyan.org/view/260164/251745 your first coffeescript, Part 1: getting started
The little book on coffeescript-syntax island205 this article is translated from Chapter 1st of the little book on coffeescript. This book is an open-source project on GitHub that uses the MIT authorization protocol. Then translate it so that more people can access coffeescript and use the MIT authorization protocol. Please correct the translation.
What is coffeescirpt?
Coffeescript is a small language that is compiled into JavaScript. Its Syntax style is influenced by ruby and python. Many features are based on these two languages. We write this book to help you learn coffeescript, understand the best practices, and help you start to create interesting client programs. This book is very small and has only five chapters, but it is sufficient for small languages like coffeescript.
Coffeescript * is not a superset of * JavaScript, so although you can use an external JavaScript class library in coffeescript, If you compile the current JavaScript directly before conversion, A syntax error occurs. The compiler converts the coffeescript code to the relative JavaScript code, so that it does not need to be explained at runtime.
First, clarify some misunderstandings. Javascript-related knowledge is required to handle runtime errors. To write coffeescript, you must understand JavaScript. However, the runtime errors are usually obvious. Up to now, I don't think there is any problem with ing JavaScript to coffeescript. The second problem is that I often hear about coffeescript speed. That is, the compiled JavaScript code of coffscript is slower than the equivalent pure JavaScript code. However, the actual situation does not prove to be a problem. Coffeescript seems to run at the same speed or even faster speed as the JavaScript code written by hand.
What are the disadvantages of coffeescript? Yes, the compilation step is introduced between you and JavaScript. Coffeescript is also trying to make up for this problem by generating elegant and readable JavaScript and integrating automatic compilation on the server side. Another drawback is that, as a new language, the Community is still relatively small at present. Finding a partner who understands this language will take you a lot of time. Of course, coffeescript is developing rapidly, and the related IRC list is also a talented person. If you have any questions, you will get quick answers.
The usage of coffeescript is not limited to browsers. It is also very good to use it on the server that implements JavaScript, for example, on node. js. Also, coffeescript is becoming more and more widely integrated. For example, it is already the standard of rails3.1. Now is the time to start learning coffeescript. The time you spend learning this language will save you a lot of time in the future.
Install
Have you ever wanted to run javascript through the command line? No, but coffeescript may change the status quo. With node. JS, you can run javascript through the command line or use JavaScript as an integral part of the execution script. This main function of node. js allows the execution of coffeescript code on the command line. It provides the runtime required by the coffeescript Compiler (written using coffeescript.
The first step is to install node. js with several installation options. You can compile the source code or run one of the installation programs that can be used in various systems. Run node-V through the command line to confirm that node. js has been installed and is in the path.
Node. js brings you an extra benefit: node Package Manager (NPM ). Run NPM-V through the command line to confirm that NPM has been installed and is in the path. Then, follow the steps below to install coffeescript using NPM.
1. Run NPM install -- global coffee-script through the command line.
-- The Global tag makes coffeescript available for the whole system, not just for a specific project.
D:\work\js>npm install --global coffee-script
npm http GET https://registry.npmjs.org/coffee-script npm http 200 https://registry.npmjs.org/coffee-script npm http GET https://registry.npmjs.org/coffee-script/-/coffee-script-1.2.0.tgz npm http 200 https://registry.npmjs.org/coffee-script/-/coffee-script-1.2.0.tgz C:\Users\Administrator\AppData\Roaming\npm\coffee -> C:\Users\Administrator\AppD
ata\Roaming\npm\node_modules\coffee-script\bin\coffee
C:\Users\Administrator\AppData\Roaming\npm\cake -> C:\Users\Administrator\AppDat
a\Roaming\npm\node_modules\coffee-script\bin\cake
coffee-script@1.2.0 C:\Users\Administrator\AppData\Roaming\npm\node_modules\coff
ee-script
2. The NPM command should output information such as/usr/bin/coffee->/usr/lib/node_modules/coffee-script/bin/coffee.
NPM created a shortcut in/usr/bin, so now the coffee executable file is in the correct path, which is the coffeescript compiler and interpreter.
3. to verify that the coffee execution file is already in the path, run coffee-V through the command line.
The last step is to confirm that the coffeescript environment has been correctly set. To enable coffeescript for any started node. JS processes are available. You need to add them to node. in the so-called node_path of JS, node. JS will search for node_path to obtain some modules (Libraries ).
The example in this article is mainly to use node. js as the runtime of coffeescript executable files. The easiest way is to simply add all NPM modules to node_path. To locate the NPM module, enter npm ls-G, you need to add an environment variable that points node_path to this position. For example, if npm ls-G outputs/usr/lib, the module is located in the/usr/lib/node_modules directory. To set a node_path environment variable, run export node_path =/usr/lib/node_modules.
You can add the preceding command to the startup script (for example ~ /. Bash_profile) to further simplify these tasks. To verify the modification, run node to start a node. JS shell, then enter require ('coffee-script'), node. the JS shell should load the coffeescript library. If the execution is okay, the coffeescript environment will be available at any time. Now you can start exploring coffeescript from the compiler.