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
  • P12: node Implements static server ~ Content-Type optimization
  • P13: Node implements static server ~ accept-encoding and Content-encoding
  • P14: Node implements the static server ~ range request

To initiate a request to the server in addition to a request to get all the content back, but also declare that I want to request to determine the scope of the content, from how many bytes to how many bytes, the server after getting the corresponding request, from get the corresponding file, get the corresponding bytes back to the client. (You can use this to achieve segmentation download function)

range

  • RequestHeaders add a range object to the request header and define the range.

    range:bytes = [ start ] - [ end ]
    Copy the code
  • RequestHeaders set accept-ranges in the request header. What format can be processed by the server

    Accept-Ranges:bytes
    Copy the code
  • The RequestHeaders request header sets the content-range to indicate what format to return, where to start and where to end, and how much

    Content-Range:bytes start-end/total
    Copy the code

The specific implementation

addheader/range.js

/** * @exports = (totalSize, req) / / module.exports = (totalSize, req) Res) => {const range = req.header['range'] // Check if range (! range) { return { code: 200 } } const sizes = range.match(/bytes=(\d*)-(\d*)/) const end = sizes[2] || totalSize - 1 const start = sizes[1] || TotalSize - end / / judge need to intercept the end of the start value is correct if (start > end | | start < 0 | | end > totalSize) {return {code: Res.setheader (' accept-range ', 'bytes') res.setheader (' content-range ', 'bytes ${start} - ${end} / ${totalSize}') res.setheader (' content-length ', end-start) return {code: 206, start: parseInt(start), end: parseInt(end) } } ```Copy the code

Introduce and userange.js

Curl up

Curl is a command line tool that uploads or downloads data and displays it using a specified URL.

  • Download address

The effect

  • performThe curl -i http://127.0.0.1:6969/README.md

You can see that the full data for the file is returned

  • Get range dataCurl -r 0-6 - I http://127.0.0.1:6969/README.md

As you can see, we’re intercepting 0 to 6 characters, 768 characters in total

The truncated character is # node (space is one character)

close