【问题标题】:Return a zip file from nodejs function从 nodejs 函数返回一个 zip 文件
【发布时间】:2018-07-31 01:24:09
【问题描述】:

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

现在,当我的服务收到 curl request 时,我需要将此 zip 文件作为 response 发送。我通读了类似的问题,但他们建议如何在客户端下载,不知道如何在这里使用它们。

我的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. 
});

【问题讨论】:

    标签: node.js zip


    【解决方案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}`))
    

    【讨论】:

    • 感谢您的快速响应和有关同步代码的 cmets。肯定有价值。我没有意识到我可以通过 readStream 将它作为普通文件发送。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多