In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
Using Nodejs to build a Web server is a more comprehensive introduction to learning Node.js, because the implementation of Web server requires several more important modules in Nodejs: http protocol module, file system, url parsing module, path resolution module, and 301redirection technology, etc., let's learn how to build a simple Web server.
As a Web server, you should have the following functions:
1. The Web page ending in .html / HTM can be displayed.
2. You can directly open the contents of files ending with .js / .css / .json / .text.
3. Display picture resources
4. Automatically download files ending with .apk / .docx / .zip
5, such as http://xxx.com/a/b/, then look for b directory to see if there is index.html, if so, display, if not, list all the files and folders under that directory, and can be further accessed.
6, such as http://xxx.com/a/b, redirect to http://xxx.com/a/b/ for 301, which can solve the problem of misplaced internal resource references.
Introduce several modules that need to be used:
one
two
three
four
five
six
seven
eight
/ / http protocol module
Var http = require ('http')
/ / url parsing module
Var url = require ('url')
/ / File system module
Var fs = require ("fs")
/ / path resolution module
Var path = require ("path")
Create a service and listen on the specified port:
one
two
three
four
five
six
seven
eight
/ / create a service
Var httpServer = http.createServer (this.proce***equest.bind (this))
/ / listen to the service on the specified port
HttpServer.listen (port,function () {
Console.log ("[HttpServer] [Start]", "runing at http://"+ip+":"+port+"/");"
Console.timeEnd ("[HttpServer] [Start]")
});
When creating a service, you need to pass an anonymous function proce***equest to process the request. Proce***equest receives two parameters, request and response. The request object contains all the contents of the request, and response is used to set the response header and respond to the client.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty
thirty-one
thirty-two
thirty-three
thirty-four
thirty-five
thirty-six
thirty-seven
thirty-eight
thirty-nine
forty
forty-one
forty-two
forty-three
forty-four
forty-five
forty-six
forty-seven
forty-eight
forty-nine
fifty
fifty-one
fifty-two
fifty-three
fifty-four
fifty-five
fifty-six
fifty-seven
fifty-eight
fifty-nine
sixty
sixty-one
sixty-two
sixty-three
sixty-four
sixty-five
sixty-six
sixty-seven
sixty-eight
sixty-nine
Proce***equest:function (request,response) {
Var hasExt = true
Var requestUrl = request.url
Var pathName = url.parse (requestUrl) .pathname
/ / A pair of requested paths are decoded to prevent Chinese garbled
PathName = decodeURI (pathName)
/ / if there is no extension in the path
If (path.extname (pathName) =') {
/ / if it does not end with /, add / and make a 301 redirection
If (pathName.charAt (pathName.length-1)! = "/") {
PathName + = "/"
Var redirect = "http://"+request.headers.host + pathName"
Response.writeHead (301, {
Location:redirect
});
Response.end ()
}
/ / add a default access page, but this page does not necessarily exist and will be dealt with later
PathName + = "index.html"
HasExt = false; / / tag the default page is automatically added by the program
}
/ / get the relative path of the resource file
Var filePath = path.join ("http/webroot", pathName)
/ / get the document type of the corresponding file
Var contentType = this.getContentType (filePath)
/ / if the file name exists
Fs.exists (filePath,function (exists) {
If (exists) {
Response.writeHead (200,{ "content-type": contentType})
Var stream = fs.createReadStream (filePath, {flags: "r", encoding:null})
Stream.on ("error", function () {
Response.writeHead (500,{ "content-type": "text/html"})
Response.end ("500 Server Error")
});
/ / return the contents of the file
Stream.pipe (response)
} else {/ / Filename does not exist
If (hasExt) {
/ / if the file is not automatically added by the program, return 404 directly
Response.writeHead (404,{ "content-type": "text/html"})
Response.end ("404 Not Found")
} else {
/ / if the file is automatically added by the program and does not exist, the user wants to access the list of files in that directory
Var html = ""
Try {
/ / user access directory
Var filedir = filePath.substring (0text filePath.lastIndexOf ('\'))
/ / get the list of files under the user access path
Var files = fs.readdirSync (filedir)
/ / list all the files under the access path and add hyperlinks for further access
For (var i in files) {
Var filename = files [I]
Html + = "" + filename+ ""
}
} catch (e) {
Html + = "the directory you accessed does not exist"
}
Response.writeHead (200,{ "content-type": "text/html"})
Response.end (html)
}
}
});
}
There are several key points in the request handling function that need to be mentioned:
If there is Chinese in the path, the browser will encode it automatically (English will not change, Chinese will change), so after receiving the address, you need to decode the address, otherwise the final path does not match the real path.
When the access path does not end with a specific file and does not end with /, it needs to be redirected with / to indicate the current directory, otherwise the static resources under the current path will not be found
If the access path is a directory, all files and folders under that directory are listed and can be accessed by clicking. In order to make the Chinese directory display properly, set charset=utf-8 in header.
This is the core code, about 140 lines, the complete code has been uploaded to gi th u b: ht t p s: / / gi th u b. C om / g i t-on epixel/Node
If you want to run demo, open cmd to change to the root directory and run node start.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.