如何在节点js中发送响应后调用函数

时间:2017-04-04 09:31:09

标签: node.js aws-sdk

下载Zip文件后,我需要调用ProcessZip文件的另一个函数。但是我无法在ProcessZipFile()

之后触发功能.send()
app.get('/', function (req, res) {
  DownloadZipFile();
});


function DownloadZipFile() {

    var file = fs.createWriteStream('./tmp/student.tar.gz');

    s3.getObject(params
.on('httpData', function (chunk) {

    file.write(chunk);

   })
.on('httpDone', function () {

    file.end();

   })
.send();
   }

function ProcessZipFile() {
     //.....
}

2 个答案:

答案 0 :(得分:0)

据我所知,在向浏览器发送响应后,您无法调用函数。因为路线已经完成。我有2个想法。

1:将您的DownloadZipFile()作为中间件,并在成功时转到ProcessZipFile(),然后发送回复()

2:创建一条新路线,您可以拨打ProcessZipFile()并通过ajax从前端呼叫此路线

答案 1 :(得分:0)

NodeJS设计为set_index,这意味着大多数I / O操作都是异步的。您不能简单地在ProcessZipFile()后拨打success,因为这会在下载完成之前触发function downloadZipFile(s3Params, downloadPath, callback) { const file = fs.createWriteStream(downloadPath); s3 .getObject(s3Params) .on('httpData', function(chunk) { file.write(chunk); }) .on('success', function() { // download succeeded -> execute the callback to proceed callback(null); }) .on('error', function(err) { // download failed -> execute the callback to notify the failure callback(err); }) .on('complete', function() { // close the file regardless of the download completion state file.end(); }) .send(); } function processZipFile(filePath, callback) { // Process the file // Remember to call `callback` after completion } app.get('/', function (req, res) { const s3Params = { ... }; const filePath = './tmp/student.tar.gz'; downloadZipFile(s3Params, filePath, function(err) { // this callback function will be executed when the download completes if (err) { res.status(500).send('Failed to download the file.'); } else { processZipFile(filePath, function(err) { // this callback function will be executed when the file is processed if (err) { res.status(500).send('Failed to process the file.'); } else { res.send('File is downloaded and processed.'); } }); } }); }); 。相反,您应该在Ball事件处理程序中调用该函数,该函数将在下载完成时执行。



draw()