Koa source reading [3]-koa-send and its derivation (static)

Source: Internet
Author: User

koaThe fourth reading of the source code relates to providing file data to the interface requester.

First article: KOA Source Reading-0
The second article: KOA source reading -1-koa and Koa-compose
The third article: KOA source reading -2-koa-router

Handling static files is a tedious task, because static files are all from the server, and it is certainly not possible to release all permissions for the interface to read.
The verification of various paths, the matching of permissions, is a place to take into account.
koa-sendand the koa-static middleware that helps us deal with these tedious things.
koa-sendis koa-static the basis that can be NPM seen on the interface, static dependencies contained in the koa-send .

koa-sendIt is mainly used for more convenient processing of static files, and unlike koa-router middleware, it is not directly injected as a function into app.use the.
Instead, it is called in some middleware, passing in the location of the current request Context and the file, and then implementing the function.

Koa-send's GitHub Address

Native file read, transmit mode

In Node , if you are using native fs modules for file data transfer, this is roughly the case:

Const FS      = require (' FS ') const KOA     = require (' Koa ') const Router  = require (' Koa-router ') ) const app     new  Koa () const router  new  router () const file    = './test.log 'const port    = 12306router.get ('/log  ', ctx = = fs.readfilesync (file). toString ()   == = Console.log (' Server Run as http:///127.0.0.1:${port} '))

or createReadStream replace readFileSync is also possible, the difference will be mentioned below

This simple example operates on only one file, and if there are many files that we want to read, it may even pass through the interface parameters.
So it's hard to guarantee that this file must be real, and we might need to add some permission settings to prevent some sensitive files from being returned by the interface.

Router.get ('/file ', CTX ={const {fileName}=ctx.query Const Path= Path.resolve ('./xxx '), FileName)//Filter hidden files  if(Path.startswith ('. ')) ) {Ctx.status= 404return  }  //determine if a file exists  if(!Fs.existssync (path)) {Ctx.status= 404return  }  //BalabalaConst RS=fs.createreadstream (path) ctx.body= RS//KOA did the processing for stream type, the details can be seen in the previous KOA})

After adding a variety of logic judgments, it is much safer to read the static files, but this is only handled in one router .
If there is more than one interface to read a static file, there is bound to be a lot of repetitive logic, so refining it into a common function will be a good choice.

The way of Koa-send

This is the koa-send thing to do, providing a very well encapsulated middleware for handling static files.
Here are the two most basic examples of use:

Const PATH = require (' path '= require (' koa-send ')//  for a file under a path get router.get ('/ File ', async CTX = {  await send (CTX, Ctx.query.path, {    './public ')  })//  get router.get for a file ('/index ', async ctx = {  './public/index.log ')}) 

Suppose our directory structure is like this, simple-send.js to execute the file:

. ├──public│   ├──a.log│   ├──b.log│   └──index.log└──simple-send.js

/file?path=XXXyou can easily access the public files below.
and access /index to /public/index.log the contents of the file.

Features provided by Koa-send

koa-sendProvides a lot of convenient options, except for the usual root , there are about 10 small options to use:

Options type default desc
maxage Number 0 Set the number of milliseconds the browser can cache
Corresponds to Header :Cache-Control: max-age=XXX
immutable Boolean false Notifies the browser that the URL corresponds to a resource that is immutable and can be cached indefinitely
Corresponds to Header :Cache-Control: max-age=XXX, immutable
hidden Boolean false Whether to support read of hidden files
.Files that begin with are called hidden files
root String - Set the root directory of the static file path, and any files outside that directory are forbidden.
index String - Set a default file name, which takes effect when accessing the directory and is automatically stitched to the back of the path (there is a small egg)
gzip Boolean true If the provider is supported by the client gzip and there is a .gz file with the same name as the suffix, the file is passed .gz
brotli Boolean true logical Ibid, if brotli .br a file with the same name as the suffix is supported and exists
format Boolean true The end of the path will not be strong after opening / , /path and /path/ represents a path (only path valid in the case of a directory)
extensions Array false If an array is passed, an attempt is made to match all the suffixes of the file in the array item , to which file to read
setHeaders Function - Used to manually specify some Headers , not very meaningful
The specific performance of the parameters

Some of the parameters can be combined to achieve some magical effect, some parameters will affect, there are Header some parameters are used to optimize performance, similar gzip and brotli options.

koa-sendThe main logic can be divided into these pieces:

    1. pathCheck for path validity
    2. gzipApplication of equal compression logic
    3. File suffix, default entry file matching
    4. Read file data

There is this logic at the beginning of the function:

Const RESOLVEPATH = require (' Resolve-path ') const {Parse}= Require (' path ') AsyncfunctionSend (CTX, path. opts ={}) {const Trailingslash= Path[path.length-1] = = = '/'Const Index=Opts.index//the initial value settings for various parameters are omitted herePath=Path.substr (Parse (path). Root.length)// ...  //Normalize PathPath = decode (path)//the internal call is ' decodeURIComponent '  //This means that passing in an escaped path is also a good way to use it.  if(index && trailingslash) path + =Index Path=Resolvepath (root, path)//hidden file support, ignore  if(!hidden && Ishidden (root, path))return}functionIshidden (root, path) {path=path.substr (root.length). Split (Sep) for(Let i = 0; i < path.length; i++) {    if(Path[i][0] = = = '. ')return true  }  return false}

Path check

The first is to determine whether the incoming is path a directory, (the end is considered to be / a directory).
If it is a directory, and there is a valid index parameter, it will be index stitched to the path rear.
This is probably the operation:

Send (CTX, './public/', {  ' index.js '})//  ./public/index.js

Resolve-path is a package used to process paths that help filter out some of the exception's paths path//file , /etc/XXX such as malicious paths, and return the absolute path after processing.

isHiddenUsed to determine if hidden files need to be filtered.
Because the . files that begin with are considered to be hidden, and the beginning of the same directory is . considered to be hidden, so there is the isHidden implementation of the function.

In fact, I personally think that the use of a regular can solve the problem. Why do you want to split the array?

function Ishidden (root, path) {  = path.substr (root.length)  returnnew  REGEXP (' ${sep}\\. '). Test (PATH)}

has been submitted to the Community PR .

Compressed open and folder handling

After this piece of code is executed, we get a valid path,(if it is an invalid path, it resolvePath throws an exception directly)
The next thing to do is to check if there is a usable compressed file, there is no logic here, it is simple exists operation, and Content-Encoding the modification (to turn on compression).

Suffix matching:

if(Extensions &&!/\. [^/]*$/.exec (PATH)) {Const LIST =[].concat (extensions) for(Let i = 0; i < list.length; i++) {Let ext=List[i]if(typeofExt!== ' string ') {      Throw NewTypeError (' option extensions must be array of strings or false ')    }    if(!/^\./.exec (EXT)) ext = '. ' +extif(Await fs.exists (path +ext)) {Path= Path +ext Break    }  }}

You can see that the traversal here is done exactly as we call it in the order in which it send was passed in, and is also compatible with the . symbol.
In other words, such calls are valid:

Await send (CTX, ' path ', {  extensions: ['. js ', ' ts ', '. TSX ')})

If the suffix can be matched to a real file after it has been added, it is considered a valid path, and then break the operation, which is what the document says: First found is served. .

After this part of the operation will be a directory detection, to determine whether the current path is a directory:

Let statsTry{Stats=await Fs.stat (path)if(Stats.isdirectory ()) {if(Format &&index) {Path+= '/' +Index Stats=await Fs.stat (path)}Else {      return    }  }} Catch(ERR) {const NotFound= [' ENOENT ', ' enametoolong ', ' Enotdir ']  if(Notfound.includes (Err.code)) {ThrowCreateerror (404, Err)} Err.status= 500ThrowErr}

A little egg.

Can find a very interesting thing, if you find that the current path is a directory, and explicitly specified format , then you will try to splice again index .
This is the egg that is mentioned above, when our public path structure looks like this:

└──public    └──index        └──index # actual file Hello

We can get to the bottom of the file data in a simple way:

Router.get ('/surprises ', async ctx = {  '/', {        './public ', ' Index '   })}) // > Curl http://127.0.0.1:12306/surprises // Hello

Here is the use of the above several logical processing, the first is trailingSlash the judgment, if the / end will be spliced index , and if the current path match is a directory, and then splicing once index .
So a simple / addition to index the parameters can be directly obtained /index/index .
A small egg, which should seldom be played in actual development.

The final read file operation

Finally came to the file read the logical processing, the first is to invoke setHeaders the operation.

Because through the top layer of filtering, what you get here is path send not the same path that was passed in when you called path .
However, there is no need to do this in the setHeaders function, as you can see that the actual return is made at the end of the function path .
We can send set it up after the execution is complete, as the official readme wrote and doing it after is too late because the headers are already sent. .
This does not need to worry, because koa the return data are put ctx.body in, and body the resolution is all the middleware after all the implementation of the process will not be processed.
This means that all middleware will not start sending the request body until after it has been executed http , before this setting Header is valid.

if(setheaders) setheaders (ctx.res, path, stats)//StreamCtx.set (' Content-length ', Stats.size)if(!ctx.response.get (' last-modified ')) ctx.set (' last-modified '), Stats.mtime.toUTCString ())if(!ctx.response.get (' Cache-control ') {Const Directives= [' max-age= ' + (maxage/1000 | 0)]  if(immutable) {Directives.push (' Immutable ')} ctx.set (' Cache-control ', Directives.join (', '))}if(!ctx.type) Ctx.type = Type (path, encodingext)//the data type returned by the interface, and the file suffix is removed by defaultCtx.body =fs.createreadstream (path)returnPath

And both the top and the above are maxage immutable in effect here, but note that if the Cache-Control value already exists, koa-send it will not be overwritten.

The difference between using stream and using ReadFile

At the end of the body assignment can be seen, is used Stream instead of, the readFile use of Stream transmission can bring at least two benefits:

    1. The first way, if it is a large file, after the completion of the read will be temporarily stored in memory, and toString there is a length limit, if it is a huge file, the toString call will throw an exception.
    2. The first way to read the file is to be returned to the interface caller after all the data has been read, and the interface is in the state during the reading of the data, Wait and no data is returned.

You can do a demo like this:

Const HTTP = require (' http ') Const FS= Require (' FS ') Const FilePath= './test.log 'Http.createserver ((req, res)= {  if(Req.url = = = '/')) {res.end (' )  } Else if(Req.url = = = '/sync ')) {Const data=Fs.readfilesync (FilePath). toString () res.end (data)}Else if(Req.url = = = '/pipe ')) {Const RS=Fs.createreadstream (FilePath) rs.pipe (res)}Else{res.end (' 404 ')}). Listen (12306, () = Console.log (' Server Run as http://127.0.0.1:12306 '))

First visit the homepage http://127.0.0.1:12306/ into an empty page (mainly lazy to do CORS ), and then in the console call two fetch can get this comparison results:


It can be seen that the downstream transmission of the same time, the use readFileSync of the way will increase a certain amount of time Waiting , and this time is the server in the file read, the length of time depends on the size of the file read, and the performance of the machine.

Koa-static

koa-staticis a koa-send shallow package based on.
As you can see through the above example, the send method needs to be called in the middleware itself.
Manually specifying the send corresponding path parameters, which are also repetitive operations, koa-static encapsulates the logic one at a time.
So that we can do the static file processing by registering a middleware directly, and no longer need to care about the parameter reading and other problems:

Const KOA = require (' Koa 'new  Koa () app.use (Require (' koa-static ') (root, opts))

optsis passed in koa-send , only the first parameter is used root to overwrite it opts root .
And added some details of the operation:

    • Default adds aindex.html
      if false) Opts.index = Opts.index | | ' Index.html '

    • By default only for HEAD and GET two kinds ofMETHOD
      if (Ctx.method = = = ' HEAD ' | | ctx.method = = = ' GET ') {//  ...}

    • Add an defer option to decide whether to execute other middleware first.
      If it is defer false , it is executed first send , and the static file is preferred.
      Otherwise, it waits until the rest of the middleware executes and determines that the other middleware does not process the request to find the corresponding static resource.
      Just specify root that the rest of the work is given koa-static , and we don't have to worry about how the static resources should be handled.
Summary

koa-sendAnd koa-static It's two very lightweight middleware.
The logic itself is not too complex, that is, some repetitive logic is refined into the middleware.
But it does reduce the number of tasks in daily development, allowing people to focus on the business rather than the edge corners.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.