Related articles

  • P01: Node.js tutorial from a practical perspective
  • P02: Basic node usage
  • P03: Node built-in module PATH
  • P04: Buffer for nodeAPI
  • P05: Events of node built-in module
  • P06: Node built-in module FS (1)
  • P07: Node built-in module FS (2)
  • P08: Node implements static server ~ create project
  • P09: Node implements static server ~ Hello HTTP
  • P10: Node implements static server ~ static file or folder reading
  • P11: Node to achieve static server ~ preliminary optimization experience

The current project needs to manually modify the address bar to achieve the operation, which is too programmer, no wonder there is no object. Let’s optimize the experience and never use a new Object again

Make the project work

Now we need to turn the address bar action into a click action, and first we should print the code as a Web page

The output page

  • We’ve already talked about how to output pages, but this time the requirements have changed slightly. We need to output a dynamic page, how to achieve?

    • Output dynamic pages are nothing more than strings, and you can choose to concatenate them one by one manually
    • You can chooseart-templateAnd other excellent string operation library
    • Select the template string to use this time
  • Create the template folder in the root directory and create dir.js again with the following code:

    • It is important to note that when writing a function, template, or library that is being called, the incoming value should be evaluated and prompted accordingly. This is conducive to later maintenance and use by others
    /** ** @param {*} Data object Mandatory */functionDir(data) {/** * To determine whether data is an object * It is important to note that when writing the function, template or library to be called, it is necessary to judge the incoming value and give corresponding hints * so as to facilitate later maintenance and other people's use */if (Object.prototype.toString.call(data) === '[object Object]') { const html = ` <! DOCTYPE html> <html lang="en">
           <head>
               <meta charset="UTF-8">
               <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
               <meta http-equiv="X-UA-Compatible" content="ie=edge">
               <title>Document</title>
           </head>
           <body>
            <a href="https://www.baidu.com/"</a> </body> </ HTML >return html
          } else {
            return 'Parameter type error'
          }
        }
        module.exports = Dir
    
        ```
    Copy the code
  • You also need to modify the route.js subordinate to the header file

    <! --> const Dir = require('.. /template/dir') <! // awaitres.end (file.join())', '))
      awaitRes.end(Dir({}))
    Copy the code
  • The output

    • It looks like the output page elements are ok, but instead of the HTML we want, it’s plain text
    • You only need to modify the route.js subordinate to the header file to output a normal Web page
    awaitRes.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
    Copy the code
    awaitRes.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
    Copy the code

Output the required dynamic pages

  • Dir. Js is modified as follows

    <a href="https://www.baidu.com/"> baidu < / a >Copy the code

    To:

     ${data.files.map((item) => {
        return `<a href="${data.dir + '/' + item}">${item}</a>`
      })}
    Copy the code
  • Route.js is modified as follows

     awaitRes.end(Dir({}))
    Copy the code

    Change to:

      const data = {
        title: path.basename(filePath),
        dir: path.relative(conf.root, filePath),
        files: files.toString().split(', '} awaitres.end (Dir(data))Copy the code
  • The output effect

    • Folder and file output
    • But clicking on a file in a subfolder will not output the correct file content
    • Handling path issues

    As can be seen from the screenshot, there is one more SRC in the path. In fact, if we click the path deeper, there will be another one, because the path we calculated is not relative to the root path

    ``` const data = { title: path.basename(filePath), dir: path.relative(conf.root, filePath), files: Files.tostring ().split(',') // replace with array} ``` ``` const dir = path.relative(conf.root, filePath) const data = {title: path.basename(filePath), dir: dir ? '/${dir}' : ', // Note that 'path.relative' is calculated relative to the root path, and true access to the root path returns empty files: files.toString().split(',') // replace with array} ''Copy the code

Beautify the page

The ability to output dynamic pages has been implemented, but as a front end, the page should not only be usable, but also beautiful

  • dir.jsIs amended as:
    /** ** @param {*} Data object Mandatory */functionDir(data) {/** * To determine whether data is an object * It is important to note that when writing the function, template or library to be called, it is necessary to judge the incoming value and give corresponding hints * so as to facilitate later maintenance and other people's use */if (Object.prototype.toString.call(data) === '[object Object]') { const html = ` <! DOCTYPE html> <html lang="en">
       <head>
           <meta charset="UTF-8">
           <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
           <meta http-equiv="X-UA-Compatible" content="ie=edge">
           <title>${data.title}</title>
           <style>
                a {
                    font-size: 20px;
                    padding: 4px 10px;
                }
            </style>
       </head>
       <body>
        ${itemFn(data)}
       </body>
       </html>
       `
        return html
      } else {
        return 'Parameter type error'}}function itemFn(val) {
      let tem = ' '
      val.files.map((item) => {
        tem += `
        <div>
            <a  href="${val.dir + '/' + item}">${item}</a>
        </div>
        `
      })
      return tem
    }
    module.exports = Dir
    
    Copy the code
  • The effect

close