JS to the end: node learning Note 4

Source: Internet
Author: User

Using node to do web development

Nonsense: Speaking of Web development, This really is my old line, from the computer field I learned the first language is php, to later the company used the asp. net platform, and then to the school push the Java EE platform, then self-taught a little ruby on the rails platform, Until now, Node. JS does not have to go around the web development of the big hole! (in fact, I have always wanted to do embedded, a period of crazy obsession with C language, ==| | | )。

HTTP vs. TCP

The last time a chat room demo was developed using Node. Js's net (TCP) module. Simply using the original TCP protocol, it can be said that TCP is the originator of the http,smtp,ftp, the subsequent application layer protocol is based on the TCP/IP protocol Extension.

The HTTP that is discussed next is the TCP upper Layer.

The difference between TCP and HTTP in node

To create a TCP service:

//tcp服务require("net").createServer(function(conn){    //在创建服务后回调函数获得一个连接引用    //每一次TCP访问,甚至于http(可降级为tcp),都会产生一个基本的conn!    //我们将要在连接上做的事情,从客户端获取数据,返回数据给客户端都基于这个conn,上一章也展示了多个conn的使用}).listen(3000);

To create an HTTP service:

require("http").createServer(function(req,res){    //在创建服务后回调函数获得两个参数,分别是请求request与响应response,这很类似于Java Servlet中的HttpRequest和HttpResponse对象,其实不同语言,不同平台虽然语法,习惯,框架不同,但是基础思想都得遵循http协议规范,这就是规范的作用:使得开发统一,简单!    //req对象中有获得客户端数据的各种方法    //res对象可以向客户端发送响应数据    //每一个客户端每一次请求都会创建一对req与res!})。listen(3000);

HTTP can be degraded, but TCP is not upgradeable:
We know that browsers generally have to access the HTTP server (strictly speaking ftp), at least the TCP service is not accessible to the browser, we can test one thing: the HTTP service can be caught by the TCP client, but the TCP service cannot be requested by the HTTP Client:

Code 1:TCP Server

//这是一个tcp服务var tcp  =require("net");tcp.createServer(function(conn){    conn.write("hello world");}).listen(3000);

The browser (http Client) cannot access:

Telnet (tcp client) can be accessed to:

Code 2:http Server

//这是一个http服务var http  =require("http");http.createServer(function(req,res){    res.end("hello world");}).listen(3000);

The browser (http Client) can access:

Telnet (tcp Client) can downgrade access:

Note: If it is a Windows system telnet, it is possible that after Telnet localhost 3000 is dark and nothing, nothing is directly entered: "get/http/1.1" note GET behind the space slash space can not be less! Then there is no space behind the http, in short, you can see it at the end!

here, Our discovery is very interesting, TCP can see http, but HTTP is not able to see the TCP data, which fully illustrates that TCP is equivalent to the HTTP parent class, is more basic, simpler protocol, http more complex, degraded can be seen by tcp!

Header information for HTTP

For HTTP this protocol, the transmission can be text, binary files, HTML rich text, Xml,json and so on, we need to tell the browser what our server to you is the file, so that the browser can know how to parse the data received, And this file type is declared in content-type, Let's compare two tests to see how the browser recognizes:

return HTML directly:

var http  =require("http");http.createServer(function(req,res){    res.writeHead(200);    res.end("sss);}).listen(3000)

Unable to parse HTML H1 tag, becomes plain text output (if you remove the preceding SSS separately output a H1 tag will be the default HTML parsing by Chrome Browser)

After joining the Content-type declaration:

var http  =require("http");http.createServer(function(req,res){    res.writeHead(200,{"content-type":"text/html"});    res.end("sss);}).listen(3000);

The Hello World here is recognized as H1 tag content!

Of course, There are many content-type, here do not explain, detailed reference: http://tool.oschina.net/commons/

Return file

If every time you use Res.end () to return a string, it is inconvenient to form a complete web Page.

So you can create a new form.html in the project sibling by federating with the node FS module by reading the HTML file to separate out the HTML code.

Form.html

<! DOCTYPEHtml>lang="en">    <metacharset="UTF-8">    <title></title><body>    <formaction="">        Form Testing        <labelfor="">Name:</label>        <inputtype="text"placeholder="enter your name">    </form></body>

Index.js

varhttp= require("http");varFs= require("fs");http.Createserver(function(req,Res{    Res.Writehead( $,{"content-type":"text/html"});    FS.Createreadstream("form.html").Pipe(res);}).Listen( the);

Note: the code introduces the FS module, the file system module, through the read stream, read an HTML file, and then pipe is the meaning of "pipe", the role is to connect the I/O pipeline file stream to the res response stream (in fact, I/O pipeline), like a tap, The water is from one to the other to the Truth.

All of these flow operations are performed asynchronously, and no matter which pipe "water" slows down the operation of Node. js, node can still handle other requests! This is a good representation of Node's powerful asynchrony.

Effect

This separates the HTML code and reduces the code coupling.

Non-blocking file stream operations like this are especially useful in large file transfers, such as some pictures, and are sent to the client using Node. JS as a picture!

To access the Image:

We'll put a "psd.jpg" in the project Directory.

varhttp= require("http");varFs= require("fs");http.Createserver(function(req,Res{    Res.Writehead( $,{"content-type":"application/x-jpg"});    FS.Createreadstream("psb.jpg").Pipe(res);}).Listen( the);

With this old routine, the Chrome browser will reload the downloaded image instead of displaying it! After the download is the Picture. This is because we did not give an IMG tag to ask the browser to display this image

Surefire Plan

In order for the text to display normally, use the following code:

varhttp= require("http");varFs= require("fs");http.Createserver(function(req,Res{    //request for picture    if(req.Method == ' GET ' && req.URL.substr(-4)==". jpg"){        FS.Stat(__dirname+req.URL,function(err,Stat{            if(err|| !Stat.Isfile()){                Res.Writehead(404);                Res.End("i can't find a picture");                return;            }            Serve(__dirname+req.URL,' application/x-jpg ');        });    }Else if(req.Method=="GET" && req.URL=='/'){        Serve(__dirname+'/form.html ',' text/html ');    }Else{        Res.Writehead(404);        Res.End("the URL is missing.");        return;    }    //independent response Function    function Serve(path,Content_type){        Res.Writehead( $,{"content-type":Content_Type});        FS.Createreadstream(path).Pipe(res);    }}).Listen( the);

Effect:

This time the webpage and the picture can display normally!

This chapter has reached http, to the core of Node. js, because node is the most widely used in the HTTP service, so this chapter can not say how many of node HTTP knowledge and problems, only the next chapter to continue to talk about HTTP.

JS to the end: node learning Note 4

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.