How to download a file with Node.js (without using third-party libraries)?

后端 未结 28 1760
逝去的感伤
逝去的感伤 2020-11-22 03:37

How do I download a file with Node.js without using third-party libraries?

I don\'t need anything special. I only want to download a file from a giv

28条回答
  •  野性不改
    2020-11-22 04:05

    If you are using express use res.download() method. otherwise fs module use.

    app.get('/read-android', function(req, res) {
       var file = "/home/sony/Documents/docs/Android.apk";
        res.download(file) 
    }); 
    

    (or)

       function readApp(req,res) {
          var file = req.fileName,
              filePath = "/home/sony/Documents/docs/";
          fs.exists(filePath, function(exists){
              if (exists) {     
                res.writeHead(200, {
                  "Content-Type": "application/octet-stream",
                  "Content-Disposition" : "attachment; filename=" + file});
                fs.createReadStream(filePath + file).pipe(res);
              } else {
                res.writeHead(400, {"Content-Type": "text/plain"});
                res.end("ERROR File does NOT Exists.ipa");
              }
            });  
        }
    

提交回复
热议问题