Use node to build a simple Web server (ii) file upload

Source: Internet
Author: User

After installing node, open the folder where node is located, have a Node_modules folder, open the Node_modules folder, you can see a NPM folder and formidable this folder. If not, the node-formidable module is not installed. (node-formidable module is an external module developed by Felix Geisendörfer)

To install the node-formidable module:

CMD input->> npm install formidable

Installation succeeded:

Success: [email protected].  0.9
NPM OK


1.server.js
//end-of-service ———— simple servervarHTTP = require ("http");//in node, you can use the Require () function to load a module.varurl = require ("url");//Load URL ModulefunctionStart (route, handler) {functiononrequest (Request, response) {varpathname = Url.parse (request.url). Pathname;//Get URL address            //handler, methods of executionRoute (pathname, Handler, response,request);//Here the request is also passed to the route ...} http.createserver (ONrequest). Listen (8888); Console.log ("Server has Started ...");} Exports.start= start;//start is a method that invokes the
View Code

2.route.js

function Route (pathname, Handler, response,request) {    // matches the user's input URL, is not a method function, is the method to return the method, Error not Found 404    if (typeof Handler[pathname] = = "function") {        return< /c10> Handler[pathname] (response, request);     Else {        response.writehead ($, {"Content-type": "Text/plain" });        Response.Write ("Not Found 404 ..." );        Response.End ();     = route;
View Code

3.index.js

varServer = require ("./server");//./server get the Server.js file in the Node.exe same level directoryvarRouter = require ("./route");//Get route.js filevarRequesthandlers = require ("./handler");//Get handler.js filevarHandle = {};//make routing rules, enter/start in the URL to return the Start method in Handler.js!!!handle["/start"] =requesthandlers.start;handle["/upload"] =requesthandlers.upload;handle["/show"] = requesthandlers.show;//Add the Show method to displayServer.start (Router.route,handle); //main entrance ...
View Code

4.handler.js

/*method called in the route (node. JS does not cache the data)*//*querying a database, or a large number of calculations, can contain blocking operations. The image says, "It's blocking all the other processing work." A new node. JS module was introduced, Child_process. It is used to achieve a simple and practical non-blocking operation: EXEC (). */varexec = require ("Child_process"). exec;varQuerystrnig = require ("querystring");//querystring module, processing post datavarFS = require ("FS");//in the FS module, NODEJS provides both asynchronous and synchronous read and write methodsvarFormidable = require ("formidable");//node-formidable module. functionStart (response) {Console.log ("Request handler ' start ' was called."); varBODY = ' //here is a form form for an HTML pageEXEC ("Ls-lah",function(Error, stdout, stderr) {Response.writehead ($, {"Content-type": "Text/html" }); //BODY = stdout;Response.Write (body);    Response.End (); });}functionUpload (response, request) {Console.log ("Request handler ' upload ' was called."); varform =NewFormidable. Incomingform ();//using the methods in the Node-formidable moduleForm.uploaddir = "temp";//indicate pathform.parse (Request,function(Error, fields, files) {Console.log ("Path:" +Files.upload.path); Try        {            //Files.upload.path File            //"Temp/test.png" saves the images sent by the user to the temp directory. Test.png is the file name of the pictureFs.renamesync (Files.upload.path, "Temp/test.png"); }Catch(e) {console.log (e); } response.writehead ({"Content-type": "Text/html" }); Response.Write ("Received image:<br/>"); Response.Write ("//the URL address that src points to is: showResponse.End (); })}//executes the image file uploaded by the user. Show the pictures.functionShow (response) {Console.log ("Show was called ...."); Fs.readfile ("Temp/test.png", "binary",function(Error, file) {if(Error) {Response.writehead ({"Content-type": "Text/plain" }); Response.Write (Error+ "\ n");        Response.End (); } Else{Response.writehead ($, {"Content-type": "Image/png" }); Response.Write (File,"Binary");// binary binary binaryResponse.End (); }    });} Exports.start=Start;exports.upload=Upload;exports.show= Show;
View Code

Cmd->node Index.js

URL Input: Http://localhost:8888/start

-->upload file Submission (you can see the picture ....) )





Use node to build a simple Web server (ii) file upload

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.