Search code examples
nodejs-server

how to let user download files from node js server?


Guys how to enable users to download stuffs from node js server using it's """core module*"""


Solution

  • what's is core module?

    if is express frame,this is a download example code

    router.get('/down', function(req,res){
      let {fn} = req.query
      fn = decodeURI(fn)
      fs.access(`./static/${fn}`, function(err){
        if(!err){
          res.set({
            "Content-Type": "application/octet-stream",
            "Content-Disposition": `attachment;filename=${encodeURI(fn)}`
          })
          fs.createReadStream(`./static/${fn}`).pipe(res)
        }
      })
      
    })