Node itself can serve static files without express or any other module..?

前端 未结 5 2279
眼角桃花
眼角桃花 2021-02-20 06:28

I am beginner in the field of node js.No idea how to send simple request from url Like :- http://localhost:9999/xyz/inde.html my file hierarchy is

server.js
xyz         


        
5条回答
  •  耶瑟儿~
    2021-02-20 06:42

    Heads up for anyone attempting to serve static files without Express or any other framework:

    There is no benefit to skipping Express, in terms of performance or productivity. The only exception is to gain an understanding of how the server and client communicate with each other. Frameworks like Express abstract away all of those complexities, and beginners may not fully understand how they work.

    Here is my approach to serving static files using Node.js only. Actually, the reason I did this is because a coding test I was given stipulated no framework whatsoever.

    1. First, decide what the URL path for those static files should look like. I want mine to be accessible under /assets/ path, such as https://example.com/assets/main.css, https://example.com/assets/cat.jpg.

    2. Decide the REGEX for matching those URL. `const assetPattern = /^/assets/[a-zA-Z]+.[a-zA-Z]+/;

    The formula above will match urls which contains /assets/[filename].[file extension.

    1. Create a server with Node.js, taking a callback function as a parameter.
    // ...
    const http = require('http')
    const server = http.createServer(requestListener).
    
    1. Extract url path, get the corresponding file path and configure your server to send the correct MIME types to the browser.
    const path = require('path');
    // ...
    const requestListener = (req, response) => {
      // get the relative url for the request. For example, relative url for a request  
      // to https://example.com is /.
      const { url } = req;
      if (url.match(assetPattern)) {
      // Inside the project directory, the static files are located under the
      // /public/assets directory.
        const filePath = `./public/${url}`;
      // Get the extension name aka the string after the dot. For example, a url like 
      // https://example.com/assets/main.css will result in extension name of css.
        const extname = String(path.extname(filePath)).toLowerCase();
        const mimeTypes = {
          '.html': 'text/html',
          '.js': 'text/javascript',
          '.css': 'text/css',
          '.json': 'application/json',
          '.png': 'image/png',
          '.jpg': 'image/jpg',
          '.gif': 'image/gif',
          '.svg': 'image/svg+xml',
          '.wav': 'audio/wav',
          '.mp4': 'video/mp4',
          '.woff': 'application/font-woff',
          '.ttf': 'application/font-ttf',
          '.eot': 'application/vnd.ms-fontobject',
          '.otf': 'application/font-otf',
          '.wasm': 'application/wasm',
        };
        const contentType = mimeTypes[extname] || 'application/octet-stream';
        staticFileHandler(req, response, filePath, contentType);
      }
    }
    
    1. Serve the static files with fs module
    const fs = require('fs')
    // ...
    const staticFileHandler = (req, res, filePath, contentType) => {
      fs.readFile(filePath, (err, content) => {
        if (err) {
          res.writeHead(500);
          res.end(`Sorry, check with the site admin for error: ${err.code}`)
        } else {
          res.writeHead(200, { 'Content-Type': contentType }); // indicate the request was successful
          res.end(content, 'utf-8');
        }
      }
    }
    

提交回复
热议问题