1. Start with the simplest HTTP service

1) I wrote in the first article that it can be installed in vscode after you click on node sn to install the second one and then click on node to get the following code

var http = require("http"); http .createServer(function (request, response) { response.writeHead(200, { "Content-Type": 'text/html; charset="utf-8"' }); response.end("Hello World"); }) .listen(8081); The console. The log (" Server running at http://127.0.0.1:8081/ ");Copy the code

You can access it directly and print the results

2) Create a new app-1.js

var http = require("http"); var fs = require("fs"); Http.createserver (function (req, res) {// 1, var pathName = req.url; // if (pathname! = "/favicon.ico") { fs.readFile("./static" + pathname, (err, data) => { if (err) { res.writeHead(404, { "Content-Type": 'text/html; charset="utf-8"' }); Res.end ("404 this interface does not exist "); } res.writeHead(200, { "Content-Type": 'text/html; charset="utf-8"' }); res.end(data); }); } }) .listen(3000);Copy the code
  • After this operation We can test can be print content on http://127.0.0.1:3000/test.html

  • Of course this test. HTML is what I created under the static folder

  • However, there is a problem that needs to be solved. Direct access to this will also display a 404 page. This is not as expected http://127.0.0.1:3000

  • We need to revise it

Var pathName = req.url; // Need to add a little judgment when the page is the initial page, i.e. http://127.0.0.1:3000 display /test.html pathName = pathName == "/"? "/test.html" : pathname;Copy the code
  • suchThe initial state is solved

3) How to parse CSS JS files??

  • First of all, why can’t we identify the first question we can try to avoid me talking to myself

  • We added two other test files test.css and test.js under static and introduced them in test.html

  • Then restart Node app1.js

  • But found that CSS and JS did not work

  • Because CSS and JS are treated as HTML because the response header is set like this {” content-type “: ‘text/ HTML; charset=”utf-8″‘ }

4) So the next problem is to identify the CSS and change the response header to the corresponding CSS identify the JS and change the corresponding JS

  • Create the common.js file in the current module folder under web-server
Exports.getmine = function (extname) {switch (extname // extname) {case ".html": return "text/html"; case ".css": return "text/css"; case ".js": return "text/javascript"; default: return "text/html"; }};Copy the code
  • Reference this in app-1.js
// introduce common.js const common = require("./module/common");Copy the code

5) The next question is how do you get a suffix?

Using the Path module

  • This module is introduced in app-1.js
var path = require("path"); Extname var extName = path.extName (pathname); var mine = common.getMine(extname); var mine = common.getMine(extname); WriteHead (200, {" content-type ": "" + mine + '; charset="utf-8"' }); res.end(data);Copy the code
  • Restart Node app1.js
  • CSS and JS all work

6) There is also a problem that is not currently recognized like /json? 13427283199 this stuff

  • You need to find a way to remove the stuff behind the JSON
  • The URL module needs to be imported using url.parse(req.url).pathname
var url = require("url");
var pathname = url.parse(req.url).pathname;

Copy the code
  • Let’s write a little bit of JSON data
  • Restart Node app1.js to access it, regardless of the numbers behind it

2. The current suffixes are too few to be implemented and need to be expanded

1) First find a test.json file and place it under the data folder

{
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".gz": "application/x-gzip",
    ".h": "text/plain",
    ".gif": "image/gif"
}
Copy the code

2) Common.js writes a portion of json data

{
   const fs = require("fs");
	exports.getFileMine = function (extname) {
  fs.readFile("./data/test.json", (err, data) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log(data);
  });
};
}
Copy the code

3) app-1.js incoming data

common.getFileMine(".gif");
Copy the code
  • After executing node app1.js
  • get

  • Change in comman.jsconsole.log(data.toString())
  • After executing, you can retrieve the data in test.jsonBut how do you show it in JSON format as an object?

4) Use json.parse () in common.js


const fs = require("fs");
exports.getFileMine = function (extname) {
  fs.readFile("./data/test.json", (err, data) => {
    if (err) {
      console.log(err);
      return;
    }

    let mimeObj = JSON.parse(data.toString());
    console.log(mimeObj[extname]);
  });
};

Copy the code

5) The premise of application in app-1. Js is introduced

common.getFileMine(".gif");
Copy the code
  • Then print the type defined in test.json

3, there is a problem that needs to be solved how to display to the page?

1) This is an asynchronous process

  • Direct calls are not possible
  • Wrapped in a promise, the call is used with async and await
const fs = require("fs"); exports.getFileMine = function (extname) { return new Promise((resolve, reject) => { fs.readFile("./data/test.json", (err, data) => { if (err) { console.log(err); reject(err); // Fail to catch return; } let mimeObj = JSON.parse(data.toString()); // console.log(mimeObj[extname]); resolve(mimeObj[extname]); }); }); };Copy the code

2) App-2. Js also needs to change the await method and use async method to wrap around it

Fs.readfilesync (‘./data/test.json’) ¶

  • Add a second method, comman.js
const fs = require("fs"); exports.getFileMine = function (extname) { var data = fs.readFileSync("./data/test.json"); Parse (data.tostring ()); return mimeObj[extname]; };Copy the code
  • Restarting Node app1.js will also work

  • The file type on the page is the same

  • Give yourself a thumbs up when you see this