Friday, 15 March 2019

Express: res.download(path [, filename] [, options] [, fn]): Download the file at given path


res.download(path [, filename] [, options] [, fn])
This method used to download the file.

path: Complete path of the file.
filename: File name to be used after downloading the content
options: You can use options to set properties like lastModified, immutable, cacheControl etc., (Refer: https://expressjs.com/en/api.html#res.sendFile)
fn: It is the callback function. It is called, once the file transfer is complete (or) any error occurs.

index.js
'use strict'

const express = require('express')

const app = express()

app.get('/', (req, res) => {
 res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
 res.send('Hello World')
})


app.get('/download', (req, res) => {
 res.download('C:\\Users\\Public\\nodeExamples\\util.js', 'utilityScript.js', (err) => {
  if(err){
   console.log('Error Occured while downloading the content')
  }else{
   console.log('File downloaded successfully')
  }
 })
})

const port = 3000
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js


Open the url ‘http://localhost:3000/download’ in browser, you can able to download the contents of the file util.js



Previous                                                 Next                                                 Home

No comments:

Post a Comment