First knowledge of node. js

Source: Internet
Author: User
Tags readfile server port

For node. js or because of the project needs, the first contact was one months ago, as a front-end, I am still relatively familiar with JS, but for node (all of the node in the following refers to node. js) is ignorant, so began to look at the document online, Official website address www.nodejs.org, but all are English, looks too laborious! So the last is to Baidu!

First, like most beginners, start installing node. js, I am using a Linux version, as for the installation process of a large number of online, I do not repeat here, interested in their own search.

Like a lot of people, the first thing you see on the homepage is an example of "Hello World" in the page output:

var http = require (' http '); Http.createserver (function (req, res) {Res.writehead ($, {' Content-type ': ' Text/plain '}); Res.end (' Hello world '). Listen (1337, ' 127.0.0.1 '); Console.log (' Server running at http://127.0.0.1:1337/');

Actually now understand: this is actually creating an HTTP request listener, after receiving the browser request, return "Hello World"! Its parameter req for the requested content, res for the returned result! As for the 1337 server port, 127.0.0.1 is the server IP address!

After I tried this example earlier, I felt that I knew nothing about node. js, but I could not read English, but first went to Baidu, what is node. js exactly? How does it work?

node. JS is a platform built on the chrome JavaScript runtime to easily build fast, easy-to-scale Web applications · node. js with event-driven, non-blocking I/O models become lightweight and efficient, ideal for data-intensive real-time applications running on distributed devices-from Baidu Encyclopedia

It is important to note that JS is an event-driven asynchronous language, which for me, which rarely touches async, writes a program or brings me a lot of trouble!

After you understand the definition and usage, you'll start to actually use it. First, node uses the module mechanism to introduce the required modules when needed (you must, of course, have to install the module):

var http = require ("http");//import HTTP Module

Require () to introduce a module method, which receives a module path identified as a parameter, that is, the relative path of the module!

OK, so we can use the HTTP module:

Listens for HTTP requests and prints incoming content http.createserver (function (req, res) {Console.log (req); Res.end ();}). Listen (port, host);

There are two kinds of modules about node: One is the core module provided by node, and the other is the file module that the user writes.

The introduction of the node module requires experience: PATH ANALYSIS------------compile execution. 3 Steps! And when the module is introduced, the extension can not be written, they can be. Js,.node,.json or other extensions! Of course, if the extension is not written when it is introduced, the Require () method will complement the extension in the order of. js,. node,. JSON. When we want to introduce our own defined method as a module, we need to bind the method to exports in the file:

Create a JS file called tool, which reads as follows: Exports.setobjval = function (obj, obj2) {for (P-in obj) {obj[p] = obj2[p]; } return obj;

I defined in tool.js a function setobjval () that assigns the value of an attribute in object 2 to an attribute of the same name in Object 1, and binds it to exports. Then I am in the same folder with tool.js another JS file start.js can be introduced through the Require () method tool.js and use the Setobjval () function:

var tool = require ("./tool"), O1 = {name: "Xiaoming", Age: "All"},o2 = {name: "Xiao Wang", Age: "};tool.setobjval" (O1, O2); Console.log (o1.name);//output: Xiao Ming

Through the above example, I think we should have a general understanding of the introduction of the module! Okay, so let's talk about Nodejs's async!

Synchronization: The so-called synchronous transmission refers to the time interval between the data block and the data block is fixed, it must strictly stipulate their time relationship.

Async: The so-called asynchronous transfer refers to the time interval between a character and a character (beginning with the end of a character to the next character) that is variable and does not need to strictly limit their time relationship.

Actually, it's clear. The difference between synchronous and asynchronous is that the synchronization needs to wait for the return value of the request to come after the next program is executed, but Async does not need, it will be issued after the request, regardless of whether the request returned, will immediately execute the next program!

Here is the send request and send the message  //load HTTP Module var http = require ("http");//Set Request parameters var options = {     hostname:  ' encrypted.google.com ',    port: 443,     path:  '/',    method:  ' GET '}//sends the request and prints the returned data content Var req  = http.request (Options, function (res)  {    res.setencoding (' UTF-8 ');     res.on (' Data ', function  (data)  {         console.log (data);     });  //load Mail Module var nodemailer =  Require ("Nodemailer")  //Set Send parameters Var smtptransport = nodemailer.createtransport ("SMTP",  {    host:  "Smtp.qq.com",     secureconnection:  true,     port: 465,    auth :{         user:&nbSP; " [email protected] ",        pass: " 0000000 "     } });  //set the message parameter var mailoptions = {    to:  "[email  Protected] ",     subject: " Hello! ",     html: " Welcome to the ordinary Childe article "} //send mail and error handling Smtptransport.sendmail (mailoptions,  function (error, response)  { if (Error)  {    console.log (' Mail ' + Error);}  else {    console.log (response.message);} Smtptransport.close ();});

If the above code is executed synchronously, after sending the request, it must wait until the return value is received before executing the part of the sending message, but because of the asynchronous node, after sending the request, regardless of whether the data received, immediately followed by the code to send the message below! This is async!

Of course there are many advantages of async, but like I do not have much contact with asynchronous people, just beginning to use asynchronous language programming is undoubtedly very painful, the pain is mainly from the control of the program flow! Used to send a request, get the data, and then perform the next operation, but now it is different, asynchronous, after making the request, in order to get the data after the next step, you need not the next code written in the request callback function, such a layer of layers, to ensure that our program can run correctly, But this can lead to a problem: nesting too deep!

Nesting too deep certainly won't have much effect on your program correctness, but this will greatly reduce the readability of the code, and can maintain the line, and it is not beautiful! This is absolutely intolerable for programmers who have a little obsessive compulsive disorder, so to avoid this problem (of course, now that the framework of node. JS is already well solved) I generally use the method of using the callback function separately:

Load file module var fs = require ("FS"),//Create read profile Method ReadFile = function (callback) {//read config file, parameters are: file path, encoding, callback function Fs.readfile ( './config.json ', ' utf-8 ', function (err, data) {if (err) throw err;//error handling callback (data);//Call the ReadFile () function      callback function});        Creates a callback function for the ReadFile () function and processes the data and prints out the data function callback (res) {var r = json.parse (res); Console.log (R.host)}}//Call ReadFile () function ReadFile ();

The callback function is independent, at least in the maintenance and aesthetics still have a great change!

Although node. js as a server-side language, in many ways with the front-end JS is very different, but at least in grammar, language style and built-in methods are still the same, so for people familiar with JS, I believe you can quickly get started with node. js! Although I have only a few one months in the initial contact to actually write the project to the project completion, but some basic usage and features of node have learned a little! So here the experience and understanding of their writing to share with you, but also as one of their own study notes, convenient to view their own later! Of course, because of the contact time is not long, understand limited, master not deep and so on, may be said is not very correct, if any students see the wrong place also please correct me, thank you!

This article by the ordinary Childe original and starts in its personal blog (reprint please specify the author and the original address) Welcome to read!

First knowledge of node. js

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.