从nodejs函数返回一个zip文件

时间:2018-07-31 01:24:09

标签: node.js zip

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

现在,当我的服务获得response时,我需要以curl request的形式发送此zip文件。我读过类似的问题,但是它们建议如何在客户端下载,不确定在这里如何使用它们。

我的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 个答案:

答案 0 :(得分:1)

如果您知道zip的路径,则可以使用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}`))