Using node.js to build a simple server
Preface: The following steps are carried out under the premise of installing node. If you do not install node, please install node first and try again.
Note: If there are errors in the following code, readers are welcome to point out.
The construction steps are as follows:
1. Create server. JS (files used to build servers)
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
var mime = require('./mime'); // Load our mime.js
var config = require('./config');
const server = http.createServer(function(req,res){
var pathName = url.parse(req.url).pathname; // Get the file name "/xxx"
// Decoding Chinese to prevent scrambling
pathName = decodeURI(pathName);
// Absolute access to resources
var realFilePath = path.resolve(__dirname+ pathName);
console.log(realFilePath);
// Get the document type of the corresponding file
var ext = path.extname(pathName); // Get the suffix name, such as'.html'
ext = ext?ext.slice(1): 'notKnow'; // Remove. Symbols
//By matching the regularity set in mine.js, we can determine whether the current requested image is a picture or not.
if (ext.match(config.Expires.fileMatch)) {
var expires = new Date();
expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);
// Setting up the response head
res.setHeader("Expires", expires.toUTCString());
res.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge);
}
// Define the type MIME of an unknown document
var contentType = mime[ext] || "text/plain"; // The suffix name is mapped when it exists, and the non-existence is'text/plain'
//File content requested from the file system
fs.readFile(pathName.substr(1),function(err, data) {
if(err) {
console.log(err);
//HTTP status code 404:NOT FOUND
//Content Type:text/plain
res.writeHead(404,{'Content-Type': contentType});
}
else {
//HTTP status code 200:OK
//Content Type:text/plain
res.writeHead(200,{'Content-Type': contentType});
var content = fs.readFileSync(realFilePath,"binary"); //When interpreting pictures, the format must be binary or errors will occur
//Write the corresponding content
res.write(content,"binary"); //When interpreting pictures, the format must be binary, otherwise errors will occur.
}
//Send response data
res.end();
});
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
Relevant require documents
1. The config.js code is as follows:
exports.Expires = {
fileMatch: /^(jpeg|gif|png|jpg)$/ig, // This is just an example.
maxAge: 60 * 60 * 24 * 365
};
2. The mime.js (save the MIME type used) code is as follows:
module.exports = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
III. Operation
(1) Jump to the corresponding project file directory through the cmd command and execute the command node server.js
(2) Visit the browser and enter it in the url bar http://127.0.0.1:8081/index.html (There should be an index.html file under the folder)
Reference resources: How to Use Noejs to Create Web Server