Read Source Code of Koa-send

Jiwen Young
4 min readApr 2, 2019

koa-send is a useful tool to serve static file for Koa.js. Unlike Nginx or Apache, Node.js Server does not give us a built-in web container by which we can serve static files, so we have to make it to serve files like css, js and image. This is where koa-send works.

Before reading its source code, we first have to know how to use it.

This middleware only have one file — index.js. Let’s look into it.

The core code of it is below code, which create a read stream flow to client based on its path argument, which is the file you want to return.

Other codes will be used to setup and extends the features of this middleware.

It includes three functions:

decode

decode is used to decode encoded path, and if something go wrong, it will return -1.

type

type is used to get the type of file, according to the extname of this file, ext argument is important becuase the function will use it to get the true extname which can be used to know the type of file when .br or .gz is met.

isHidden

isHidden is used to judge if the file is hidden. It will strip off the root path of a specialized path, and then split it into an array by sep delimiter. And then, traverse this array, and if the first character of corresponding element is “.”, we know that this is a hidden file. In Javascript, you can take the string as an array, so path[i][0] is legal. Here you should know that this mechanism only works in Linux Operation System in that Windows don’t think “.filename” is a hidden file.

In the send function, options object will be formated first

and then, normalize the path

If user pass the index option, custom index file will be set

Absoulte Path is getten here.

If this is a hidden file and hidden option is set to false, the function will return

The following code is used to make the correct setup if compression file including .br and .gz is met.

You can ignore extname in your URL and the following code will try to help you. It will try to match extensions from passed array to search for file. However, I donot think this is a good idea.

The following code first get the stats object which is very helpful. And then, format the path and update the stats object according to the new path.

If setHeaders is passed in, run it to set custom header.

Finally, set Conten-Length , Last-Modified , Cache-Control and send the response to the client.

Koa.js to some degree is very like Lego. Assemble these tiny middlewares and make a meaningful product.

--

--

Jiwen Young

I am a China based developer specialized in web development and web design.