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