Use Nodejs to build a simple server

Source: Internet
Author: User
Tags clear screen readfile

Use Nodejs to build a simple server

Nodejs Advantages: High performance (read and write files) data operation ability is strong
Official website: www.nodejs.org
Verify that the installation succeeded: cmd command line input NODE-V if the display version number indicates successful installation

"Common Commands"

Toggle Drive letter D:
Go to Folder CD Nodejs
Go back to the top level directory CD.
Clear Screen CLS
Display Directory Dir
Copy file name Select right--copy
Historical operation up ARROW
Execute the File node file name (in the file folder directory)
Stop command line CTRL + C

Nodejs can use ECMAScript, read and write files, database operations, build servers
What Nodejs can not do is: DOM, BOM

Use node to build a server:

//1, the introduction of the module using the HTTP service protocol is RFC2616 Nodejs author has written, directly introduced on the linevarHTTP = require ('http');//introduction of File read-write module FSvarFS = require ('FS');//2, the creation of the parameters of the server function req is sent to the server request, RES is the server's correspondingvarHttpobj =http.createserver (function (req,res) {//write a URL where index.html is the file to be read by the server    varURL = req.url=='/'?'index.html': Req.url; //start the file read, the parameters are the full URL encoding and completion of the execution of the function, note that the front and back code needs to be consistentFs.readfile ('www/'+url,'Utf-8', Function (err,data) {//res.write Server to the corresponding, when successful, the server will transfer a data, the corresponding end of the need end        if(Err) {Res.write ('404, the page you visited does not exist');            Res.end (); }Else{res.write (data);            Res.end (); }    });});//Listening PortHttpobj.listen ( the);


Writing an SQL statement using Nodejs

//like building a server, you need to introduce a module, Mysqle is an exogenous module (pre-Download in node), the MySQL module will tell the server whether we need Add or get//1, introduced the module, here introduced a MySQL module morevarHTTP = require ('http');varFS = require ('FS');varMySQL = require ('MySQL');//2, the connection server uses Createserver, the same parameter is also req and resvarHttpobj =http.createserver (function (req,res) {varURL = req.url=='/'?'index.html': Req.url;    Console.log (URL); //provides a JSON write front-end interface to the front end//There's more addresses, usernames, passwords, and databases.    if(Url.split ('?')[0]=='/article'){        //Console.log (' I want to give the front-end data interface '); //1. Establish a connection        vardb =mysql.createconnection ({//AddressHost'localhost',            //User nameUser'Root',            //PasswordPassword"',            //DatabaseDatabase'study'        }); //3, write the SQL statement, is to tell the server when you want to request we need Add or get        varsql ='SELECT * from user'; //3. Execute SQL Return resultsdb.query (sql,function (err,data) {if(Err) {Console.log ('failed'); }Else{                //Console.log (data[0].username); //Console.log (json.stringify (data));Res.write (json.stringify (data));            Res.end ();    }        }); }Else{        //Read PageFs.readfile ('www/'+url,'Utf-8', Function (err,data) {if(Err) {Res.write ('404, the page you visited does not exist');                Res.end (); }Else{res.write (data);                Res.end ();    }        }); }});//4. Listening PortHttpobj.listen ( the);

Reprint please specify ' reproduced in Jason Qi Qi's blog http://www.cnblogs.com/jasonwang2y60/'

Use Nodejs to build a simple server

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.