Node.js download static or generated file
Do you want to download a static/dynamically generated file using Node server using express module ? Let’s begin a simple example :
Let me end your search in this article. Here is simple Node server I created :
Lets server our
data folder on node js server using app.use :
“ app.use mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches
So on above code we will be serving our files present inside `data` folder on the path
/resources . For example if there is file named
localhost:1729/resources/a.pdf will show us the pdf file on broswer that we can save or download. So this is how we can see any static file on browser and download into our local system.
For Dynamically generated file:
Similar things will be applied for dynamically generated file to download. Let’s generate a file after
/createFile get request and download it. There can be any logic according to the requirement to create file (any file). I am using simple logic to create a file for a demo. Since we are serving our
data folder, so we should save the generate files into that folder only.
When we browse
localhost:1729/createFile it will display the the link to download or see the file content , if it is displayable on browser (like txt, md files).
You can find the code discussed here in this github repository. So this is basic example for serving files in node js, we can put logic as per requirements and extend it. Any improvement and suggestions are welcome and finally thanks for reading/clapping on it.