"Node Entry" Reading notes-developing a small app with node. js

Source: Internet
Author: User
Tags tmp folder install node node server sublime text

If you want to reprint please specify the source http://blog.csdn.net/as645788

Android app Development is over, a stable, basic function of the app has been delivered to the user! I had a conversation with my boss, and then I was ready to move to node. js, and part of the front-end function goes in! hahaha ~ ~ ~ next to a full (Zuo) stack (SI) engineers, think of a little excited about it! These days have been learning new things, HTML CSS JavaScript jQuery SQL bootstrap node.js

(Well, looking at so much knowledge of the back and forth I've been messy--.) -····· )
To learn is a lot of things, time is tight, and later I know a search after the main node.js,sql and so on to find out how to write the sentence, JavaScript Learning basic grammar and key ideas (callback, closure) HTML CSS to be able to understand, jquery also try to write, here first recommend a good website, the world's largest learning site development of the local W3Schools (simple and straightforward English site, you can exercise their ability to read English documents, seemingly need to turn over the wall, Please bring your own ladder), no ladder child shoes can go to the Novice tutorial (the Chinese own translation of the site, the content is basically the same), the small spit trough: w3schools exercise too water, 6 questions basic practice are similar, up to two or three places, The final test is actually 24 choice questions, it is difficult to think of it However, it seems that the way people profit is the last certificate after the end of the study, the price is amazing 95 American knives (in foreign knowledge is indeed very valuable-. -)

Don't say more, go to the point, I was on the internet to see this "node Introduction" a total of 42 pages, while looking at the endorsement of the code to write their own, a day to see, or there are many gains.
First we want to install node. js, I use the Windows version of the installation package, download the installation directly, and then we need to decorate the sublime text 3. Here are the three goals we ultimately need to achieve.

    • Users can use our app through a browser.
    • When the user requests Http://127.0.0.1:8888/start, you can see a welcome page with a file upload form on the page.
    • The user can select a picture and submit the form, and then the file will be uploaded to Http://127.0.0.1:8888/upload, which will display the image on the page when the page is uploaded.

The final effect is this:

There is a part of the book about directly the function as a parameter to the value of the words, I think it is very good, now extracts to facilitate the understanding of what is functional programming
Behavior-Driven execution

Allow me to break away from the subject again and talk about functional programming here.

Passing a function as a parameter is not just a technical consideration. For software design, this is actually a philosophical question. Think of this scenario: in the index file, we can pass the router object in, and the server can then call the object's route function.

Like this, we pass a thing, and the server uses this to do something. hey, that thing called routing, can you get this routed for me?

But the server doesn't really need anything like that. It just needs to get things done, in fact, in order to get things done, you don't need anything, you need action. in other words, you don't need a noun, you need a verb .

After understanding the core and basic ideas in this concept, I naturally understood the function programming.

One more thing to understand about node. JS is the difference between blocking IO and non-blocking IO (using callback functions)

To put it simply, let's say we're going to a fast food restaurant with two different service modes, one is event-driven (our node server), and not (like Iis,apache). For a traditional server, after receiving your request, until he finishes your request, he will not receive the next user. When the waiter enters your order there is still a lot to do, to handle your payment, to help you pour water, and some time (not sure) to wait for the kitchen to prepare your burger. The waiter (equivalent to a thread on the server) receives only one customer at a time until the current customer's reception is completed before the next customer is received. Obviously, this is not a very efficient way, he wasted too much time waiting for the kitchen to do hamburger work. The real fast food restaurant uses another mode, when receiving your order, he will give you a number card, this number is equivalent to the callback function. Then he will go to receive the next customer. When your order is ready, the waiter will call your number and ask you to pick up the meal. This is the pattern that node uses to see how efficient he is.

Looking at the book down the road, we divided the small node. JS program into three main modules: Server (server), router (distribution handles different requests), RequestHandle (the part that actually handles the request), and the rest is the refinement of the details.

Finally paste all the source code for everyone to learn it, Windows has a pit, the pit took me two hours to find, specifically see Code

Home File Index.js

varServer= require('./server ');//Local write Server.js filevarRouter= require('./router ');varRequestHandle= require('./requesthandle ');var Handle ={};Handle["/"]= Requesthandle.start;handle['/start ']= Requesthandle.start;handle['/upload ']= Requesthandle.upload;handle['/directory ']= Requesthandle.directory;handle['/display ']= Requesthandle.display;server.start (router.route,handle);

Server.js

//Invoke node. js's own module HTTP and assign its return value to Var httpvarHTTP =require("http");varURL =require("url"); function start(route, handle) {//Using ONrequest as the callback function     function onrequest(Request, Response) {        varPathName = Url.parse (request.url). PathName;varPostdate =""; Console.log ("Request for"+ PathName +"has received.");            Route (Pathname,handle,response,request);    }; Http.createserver (ONrequest). Listen (8888); Console.log ("Server has start");} Exports.start = start;

Router.js

function  route   (pathname,handle,response,request)  { Console.log ( "start router with handle and path name is"  + pathName); if  (typeof  handle[pathname] = = =  "function" ) {return  Handle[pathname] (response,request); //node.js This method of execution is cool. } else  {Console.log ( "404 Not Find" ); Response.writehead (404 , { "Content-type" :  "Text/plain" }); Response.Write ( "404 Not Found" ); Response.End (); }}exports.route = route; 

Requesthandle.js

varexec =require(' child_process '). exec;varQueryString =require(' QueryString ');varFS =require(' FS ');varFormidable =require(' Formidable ');functionStart (response) {Console. log ("Handler ' start ' was called");//Just for the sake of learning to write HTML here, in fact, it is not so ugly to write HTML directly in the processing programvarBODY =' +' +' <meta http-equiv= ' Content-type "content=" Text/html;charset=utf-8 "> "+' +' <body> '+//The URL that defines the jump after the submit is/upload, and is a POST request' <form action= '/upload "method=" post "enctype =" Multipart/form-data "> '+' <input type= ' file ' name= ' upload ' multiple= ' multiple ' ><br/> '+' <input type= ' submit ' value= ' upload file ' > '+' </form> '+' </body> '+' ; Response.writehead ( $, {"Content-type":"Text/html"});    Response.Write (body); Response.End ();}functionUpload (response, request) {Console. log ("Handler ' upload ' was called");varform =NewFormidable. Incomingform ();//Key: You need to change the default upload path for the form, and you need to manually create the TMP folder under Windows due to permissions issues Form.uploaddir =' tmp '; Form.parse (Request,function(Error, fields, files) {Console. log (Files.upload.path);//Fs.renamesync (Files.upload.path,"/tmp/test.png");//Considering that this is a sync synchronization operation, you must capture the exception, and node. JS does not recommend a synchronous operationTry{Fs.renamesync (Files.upload.path,' Tmp/test.png '); }Catch(e) {Console. log (e); } response.writehead ( $, {"Content-type":"Text/html"}); Response.Write ('  ');      Response.End (); });}functionDisplay (response) {Console. log ("Handler ' display ' was called"); Fs.readfile ("Tmp/test.png",function(Error, file) {if(Error) {Console. log ("Sorry"); }Else{Response.writehead ( $,{"Content-type":"Image/png"});//Response.Write (data);           Response.Write (file);        Response.End ();    }; });}/*//Response to user input display methodfunctionDisplay (response,postdate) {Console. log ("Handler ' display ' was called"); Response.writehead ( $, {"Content-type":"Text/plain"}); Response.Write ("You input"+ Querystring.parse (postdate). Text); Response.End ();} */exports. start = start;exports. upload = upload;exports. directory = Directory;exports. display = display;

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Node Entry" Reading notes-developing a small app with 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.