Quickly write a simple static file server with Nodejs for 10 minutes

Source: Internet
Author: User
Tags readfile

After a few days of Nodejs, I went on to work on the front end. The problem is that I want to be on different devices to easily view the page I wrote, it is natural to think that if you can build a simple HTTP server locally, all the devices within the LAN can be accessed, which is very good. So it's hot. Implement a simple server immediately.

Requirements: Access http://192.168.1.100/index.html can return the specified Web page and its related resources (CSS,JS, picture files, etc.)

function start (route, handle) {    http.createserver (function(request, response) {        Request.addlistener (function() {            fetchfile (request, Response)})    . Listen ( 8888);}

Call the Createserver method to create a server and listen on port 8888, listen for the end event within the callback, and hand over the work that was fetched and returned to the Fetchfile function that is about to be written.

var typemap = {    ". png": "Image/png",    ". jpg": "Image/jpeg",    ". js"  : "Application/javascript",    ". css": "Text/css",    ". html": "Text/html"} 

Next, before writing fetchfile, we need a "suffix name->conent-type" table so that when the browser accesses the specified resource, we can return the content-type of the response.

varFS = require (' FS ')functionfetchfile (req, res) {varURL =Req.url Fs.readfile ("." +req.url,function(err, data) {varContentType = "Text/plain"if(!err) {            //find type of file             for(KeyinchTypemap) {                if(Req.url.match (key)) {ContentType=Typemap[key] Break}} res.writehead ($, {"Content-type": ContentType}) Res.write (data) res.end ()}Else{Res.writehead (404, {"Content-type": ContentType}) Res.end ()})}

In the final step, when we receive a request, we simply take out the requested URL, find the response content-type in Typemap, and then call the asynchronous file read method of the FS module,

    • If the file exists, we return the correct header information, attach the contents of the file, and send the response.
    • If the file does not exist, returns a 404 status code, ending the response.

Finally, don't forget to call our Start method.

Full code:

varHTTP = require ("http");functionstart (route, handle) {Http.createserver (function(Request, Response) {Request.addlistener ("End",function() {fetchfile (Request, Response)}). Listen (8888);}varTypemap = {    ". png": "Image/png",    ". jpg": "Image/jpeg",    ". js": "Application/javascript",    ". css": "Text/css",    ". html": "Text/html"}varFS = require (' FS ')functionfetchfile (req, res) {varURL =Req.url Fs.readfile ("." +req.url,function(err, data) {varContentType = "Text/plain"if(!err) {            //find type of file             for(KeyinchTypemap) {                if(Req.url.match (key)) {ContentType=Typemap[key] Break}} res.writehead ($, {"Content-type": ContentType}) Res.write (data) res.end ()}Else{Res.writehead ("Content-type": ContentType}) Res.end ()})}start ( )
Server.js

Quickly write a simple static file server with Nodejs for 10 minutes

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.