Friday, 15 March 2019
nodejs : how to send response immediately before res.end? and how to delete a file after a certain time
Hello, I have an app which will zip a array of images using loop. During the zipping, I would also want to send the status to client side. For instance, 10 images and 4 is zipping, on client: 4/10 ; I set a counter i and res.write(String(i)) before res.end("Download Completed). However, it seem like nodejs won't allow send until res.end.I got something like this on client side: 12345678910Download Completeddownload.jsconst express = require('express'); let router = express.Router(); const fetch = require('node-fetch') // to get the images const JSZip = require('jszip') // to zip them up const path = require('path'); const fs = require('fs'); const http = require('http'); const { promisify } = require("util"); const rimraf = require("rimraf") router.post('/gen-link', (req, res) => { var zip = new JSZip(); const files = [] for(let i = 0; i < req.body.imgAry.length; i++) { let urlA = req.body.imgAry[i]; let fileA = urlA.substr(urlA.lastIndexOf("/") + 1, urlA.length - 1) files.push({url: urlA, file: fileA}) } const server = async () => { // Fetch each image source let i = 0; for (const { file, url } of files) { const response = await fetch(url) const buffer = await response.buffer() zip.file(file, buffer) i++; res.write(String(i)); console.log(i); } } const path = __dirname + '/client/build/out.zip'; server().then(() => { // Set the name of the zip file in the download // Send the zip file zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true }) .pipe(fs.createWriteStream(path)) .on('finish', function () { // JSZip generates a readable stream with a "end" event, // but is piped here in a writable stream which emits a "finish" event. console.log("out.zip written."); res.end("Download link is ready"); }); }); }) The app also allow user to download that zip file from the server. And I want to delete that zip file after the user finished the download in a certain time like 1 minutes. I had tried compression or await async, but didn't work.clientside download button
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment