Reputation: 1606
I am downloading a file and sometimes file size can be big and timeout is not enough. when timeout, I would like to cancel download process because even I get a timeout error, it continues to process the file and give the following exception
_http_outgoing.js:470 throw new ERR_HTTP_HEADERS_SENT('set'); ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11)
here is my async method
router.get('/api/files/GetFile', urlencodedParser, (req, res) => {
return new Promise(function (resolve, reject) {
(async function () {
try {
var folderName = "File_" + moment().format('DD-MM-YYYY HH_mm_ss');
await routerFile.CreatePdfZip(req.query.VoucherCodes, req.query.AppNames, folderName);
var fullzipPath = './FilesToDownload/' + folderName + '.zip';
zipFolder('./FilesToDownload/' + folderName, './FilesToDownload/' + folderName + '.zip', function (err) {
if (err) {
return reject(err);
} else {
console.log('zip created');
rimraf('./FilesToDownload/' + folderName, function () {
console.log("folder has been deleted");
});
fs.readFile(fullzipPath, (err2, zipData) => {
if (err2) reject(err2);
const base64 = zipData.toString('base64');
res.setHeader('Content-type', 'application/zip');
res.type('zip');
res.end(base64, 'binary');
console.log('EXCELLENT');
});
}
});
} catch (error) {
return reject(error);
}
})();
}).catch(error => {
console.log(error);
res.send(error);
});
});
The error occurs in the line res.setHeader('Content-type', 'application/zip');
PS: router variable comesfrom const router = express.Router();
and here is the timeout set
const app = express();
app.use(timeout('2s'));
app.use(bodyParser());
app.use(haltOnTimedout);
app.use(cookieParser());
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next) {
if (!req.timedout)
next();
else {
console.log('TIMEOUT.----------------------------------------------');
}
}
What am I doing wrong here? Or is there better way to set a timeout and cancel the downloading process
PS: CreatePdfZip method takes time.
Upvotes: 0
Views: 317
Reputation: 1448
To avoid this error, you can check if the response
is already sent and sent the response only if not sent (But does not really solve/cancel download processing)
...
fs.readFile(fullzipPath, (err2, zipData) => {
if (err2) reject(err2);
if (!res.headersSent) {
const base64 = zipData.toString('base64');
res.setHeader('Content-type', 'application/zip');
res.type('zip');
res.end(base64, 'binary');
console.log('EXCELLENT');
}
});
...
Upvotes: 1