簡體   English   中英

從 nodejs function 返回一個 zip 文件

[英]Return a zip file from nodejs function

我有一個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. });

如果您知道 zip 的路徑,那么您可以使用fs.createReadStream()創建一個可讀的 stream 並使用pipe()將數據從 ZF7B44CFAFD5C52223D5498196C8A2E7Z 直接傳遞到響應。

 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}`))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM