Before jumping right into making your own storage engine, let’s discuss why we need it in the first place and some of its applications.
Here’s the link to the GitHub repo for the following tutorial.
At this point, I assume that you have a clear idea of what multer is and what it is used for. Just to be on the same page here is a quick introduction to multer in its “out-of-the-box” form:-
So basically multer is used to parse data from HTTP requests with
Content-Type
header set to multipart/formdata
. Content-Type header in an HTTP request describes the types of resources shared over the network. And these resources need special middlewares to be parsed and made available in the server-side application. Content-Type header of application/json, application/x-form-www-urlencoded, text/html
can be parsed via body-parser but multipart/formdata
needs a different middleware i.e. multer. mutipart/formdata
Content-Type means that apart from JSON or plain text data, resources may have Blob or File type fields as well. Without these middlewares, we won’t be able to use the resources sent over by the user. The req.body
we use so casually in an express app, would have always returned an empty object if it wasn’t for these middlewares.
Now that we have a fair idea about multer, let’s discuss the need for a custom storage engine and make one using TypeScript.
Storage engines are basically classes that deal with the file once they are parsed this includes storing, deleting, and modifying the original file. By default, multer comes with 2 storage engines, DiskStorage, and MemoryStorage. DiskStorage stores the file on disk at a given location whereas MemoryStorage stores the file’s content as a buffer in the application’s memory.
#typescript #javascript #coding #web-development