Serving Temporary Files with NodeJs

后端 未结 2 2137
礼貌的吻别
礼貌的吻别 2021-02-04 09:52

I am building a NodeJs SOAP client. Originally, I imagined the server (ie the node SOAP client) would allow downloading documents through a REST API (the REST API is authentica

2条回答
  •  长发绾君心
    2021-02-04 10:16

    Found two SO questions that answer my question. So apparently we don't need to use the express.static middleware. We just need the filesystem to download a file:

    app.get('/download', function(req, res){
     var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
     res.download(file); // Set disposition and send it.
    });
    

    If we want to stream and then delete follow:

    app.get('/download', function(req, res){
       var stream = fs.createReadStream('/example.pdf', {bufferSize: 64 * 1024})
       stream.pipe(res);
    
       var had_error = false;
       stream.on('error', function(err){
          had_error = true;
       });
       stream.on('close', function(){
       if (!had_error) fs.unlink('/example.pdf');
    });
    

提交回复
热议问题