node.js 18 creates a static web server http

Refer to the original article -http: //bjbsair.com/2020-03-22/tech-info/2821/
First we will explain what needs http static web server needs to implement, then we will start from node.js, agencies need module.

node.js 08 code creates a static web server http

http

http static web server

Here http static server is to create a static website, and create static web server via node.js to provide service to clients. An example of a static web server is Apache Apache directory, need only to sites related to html, css, javascript, jpg and other static resources into the next, only need to access the host name can be displayed pages.

That which we can see that static website resources include:

  • html file
  • css file
  • javascript file

The reality is that, in addition to these three major documents, most of the site resources include image files, audio files, compressed files, font files, and so on.

The static website web server needs to provide

  • http service, you can for http requests submitted by the client, returns to static pages static pages and resources needed to be used . Suppose you want to access the index.html page, the page used to image files, css style file, javascript file needs to be returned to the client browser to display. If the program returns only the html file, the browser will not display the associated images, css effect response, javascript effect may not appear.
  • http port for monitor http requests submitted by the client, port 80 is used by Apache above. Various web servers support port configurations, then we node.js is no exception, can be implemented in the program
  • Status code: For each client request, while the return page, web server returns a status code. Successfully processed the request status code 200 , and 404 indicates the file or resource was not found.

HTTP Header 中的 Content-Type

node.js 08 code creates a static web server http

http header

The figure is http response header when accessing a website. We can see this status code status code is 200, indicating that the request processed successfully. In response headers returned inside a Content-Type, there is value "text / html; charset = utf-8".

  • text / html: express return to the page format is html, html page displayed in the form of browser.
  • charset: Returns the character set of the page

Sometimes return to the page format if it is "text / plain", representation of the page in plain paper to show.

These formats are collectively referred to as MIME (Multipurpose Internet Mail Extensions) is a description of the type of message content of the Internet standards.

Depending on the file type, Content-Type need in http headers in which a value corresponding to the writing.

You may specifically define a constant in the node.js, by way of the key to obtain Content-Type The file extension.

const mimeType = {  
  '.ico': 'image/x-icon',  
  '.html': 'text/html',  
  '.js': 'text/javascript',  
  '.json': 'application/json',  
  '.css': 'text/css',  
  '.png': 'image/png',  
  '.jpg': 'image/jpeg',  
  '.wav': 'audio/wav',  
  '.mp3': 'audio/mpeg',  
  '.svg': 'image/svg+xml',  
  '.pdf': 'application/pdf',  
  '.zip': 'application/zip',  
  '.doc': 'application/msword',  
  '.eot': 'application/vnd.ms-fontobject',  
  '.ttf': 'application/x-font-ttf',  
};

The code above basically meet the definition of a resource type static website required.

Code logic and implemented

  1. Create http server through node.js, see node.js 04 http server preliminary
  2. Parsing url
  3. The access path is determined by the file or directory exists, if not, then an error status code 404
  4. If the access path to the directory, the file path is returned index.html
  5. In response to write files according to the contents of the request path, while setting Conten-type according to the resource type.

Above all logic with document processing, directory processing related code needs to be accomplished by calling the fs node.js modules, see node.js 07 file operations .

DETAILED following code segment:

http.createServer(function (req, res) {  
  // 调用url模块来解析访问的url  
  const parsedUrl = url.parse(req.url);  
  
  // 提取路径  
  const sPath = path.normalize(parsedUrl.pathname).replace(/^(\.\.[\/\\])+/, '');  
  let pathname = path.join(__dirname, sPath);  
//判断路径是否存在  
  fs.exists(pathname, function (exist) {  
    if(!exist) {  
      //如果路径不存在,则返回404  
      res.statusCode = 404;  
      res.end(`File ${pathname} not found!`);  
      return;  
    }  
  
    // 如果路径是目录,则将路径替换为目录下的 index.html  
    if (fs.statSync(pathname).isDirectory()) {  
      pathname += '/index.html';  
    }  
  
    // 根据路径读取文件,此处调用fs模块方法  
    fs.readFile(pathname, function(err, data){  
      if(err){  
        res.statusCode = 500;  
        res.end(`Error getting the file: ${err}.`);  
      } else {  
        // 获取路径后缀名  
        const ext = path.parse(pathname).ext;  
        // 根据后缀名获取响应的content-type; 这里的minType定义见上面的代码块  
        res.setHeader('Content-type', mimeType[ext] || 'text/plain' );  
        //通过end方法来结束response  
        res.end(data);  
      }  
    });  
  });  
//提供http端口监听  
}).listen(8001);

Such a static web server http code is complete, very light, compared with many languages, it can be described as a very lean.

Original articles published 0 · won praise 0 · Views 298

Guess you like

Origin blog.csdn.net/zxjoke/article/details/105084904