2017-04-04 66 views
1

下载后的压缩文件的响应后,我需要调用另一个函数ProcessZip文件。但我无法在.send()后触发功能ProcessZipFile()功能如何调派往节点JS

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() { 
    //..... 
} 

回答

0

据我知道你不能调用函数发送到浏览器的响应后。因为路线完成了。我有2个想法给你。

1:请您DownloadZipFile()作为一个中间件和成功,你去ProcessZipFile(),然后发送响应()

2:请在您调用ProcessZipFile()一条新的路线,并通过Ajax调用从前端此路线例如

0

的NodeJS被设计为non-blocking,这意味着大多数I/O操作是异步的。你不能简单地调用ProcessZipFile().send()后,因为这将下载完成之前触发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.'); 
 
     } 
 
     }); 
 
    } 
 
    }); 
 
});

+0

你可以注意到 “[回调地狱(http://callbackhell.com/)” 通过嵌套回调函数创建。要解决这个问题,你可以[使用'async'库或'Promise'(https://ciphertrick.com/2016/06/12/avoiding-callback-hell-node-js/),或['异步/在ES7中等待“](http://rossboucher.com/await)功能。 –