代码之家  ›  专栏  ›  技术社区  ›  Dreams

从nodejs函数返回zip文件

  •  0
  • Dreams  · 技术社区  · 6 年前

    我有一个 nodejs 微服务,其中我 zip 包含由代码创建的3个文件的文件夹。

    现在,我需要将这个zip文件作为 response 当我的服务 curl request . 我读过类似的问题,但他们建议如何在客户端下载,不确定如何在这里使用它们。

    我的nodejs代码是:

    var zipper = require('zip-local'); 
    app.post("/checkFunc", function(req, res) {
        zipper.sync.zip("./finalFiles").compress().save("pack.zip");
        // so now the zip is created and stored at pack.zip
        console.log("Hello);
        res.writeHead(200, { 'Content-Type': 'application/octet-stream' });   
    
        //res.send(a); //not sure how to send the zip file, if I know the path of the zip file. 
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   peteb    6 年前

    fs.createReadStream() pipe()

    const express = require('express')
    const fs = require('fs')
    const port = process.env.PORT || 1337
    const zipper = require('zip-local')
    
    const app = express()
    
    app.post('/checkFunc', (req, res) => {
        // If you're going to use synchronous code then you have to wrap it
        // in a try/catch if you don't want to crash your server. In this case
        // I'm just handling the error and returning back a 500 error with a 
        // standard response message of Internal Server Error. You could do more
        //
        // Using the Error Handling Middleware (err, req, res, next) => {}
        // you can create a more robust error handling setup.
        // You can read more about that in the ExpressJS documentation.
        try {
          zipper.sync.zip("./finalFiles").compress().save("pack.zip");
        } catch (err) {
          console.error('An error occurred zipping', err)
          return res.sendStatus(500)
        }
    
        // Create a readable stream that we can pipe to the response object
        let readStream = fs.createReadStream('./finalFiles/pack.zip')
    
        // When everything has been read from the stream, end the response
        readStream.on('close', () => res.end())
    
        // Pipe the contents of the readStream directly to the response
        readStream.pipe(res)
    });
    
    app.listen(port, () => console.log(`Listening on ${port}`))