How To Download a File Using Express

How To Download a File Using Express

·

1 min read

The syntax we use to download a file that we already have stored in our project in Express is:

<script> 
res.download(first parameter, second parameter).
</script>

The first parameter is the exact address of the file we want to download.

The second parameter is the name that we want the file downloaded to take. We fill in the second parameter when we want the file to have a different name than the original when downloaded. Alternatively, we may leave the second parameter blank, if we want to download it using the same as the original name.

Example

var express = require('express');
var router = express.Router();
// ...
router.get("/", function(req, res, next){
res.download("/public/files/files");
});

In the example, you see, we are downloading a file named "file.txt" that is stored in our /public/files folder.