我正在使用 busboy 模块上传文件。它适用于一个文件。但是,当我尝试上传多个文件时,它会引发以下错误。
Error: Can't set headers after they are sent
我知道为什么它会抛出错误,但我无法找出解决方案。以下是我的代码片段。
exports.uploadFile = function (req, res) {
console.log('Calling uploadFile inside FileUploadService');
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldName, file, fileName) {
// Get folderGuid
var folderGuid = req.params.folderGuid;
//Get folderName
var folderName = req.query.folderName;
//path of file contents
var directoryPath = fileRepositoryPath + "/" + folderGuid+"/"+folderName;
//Get location
var filePath = directoryPath + "/" + fileName;
log.debug("inside FileUploadService ::: uploadFile >> folderGuid: " + folderGuid + ", directoryPath : " + directoryPath + ", filePath : " + filePath);
//Create directory
nodefs.mkdir(directoryPath, 0777, true, function (err) {
if (err) {
log.error({err: err}, 'Error while creating recurrisve directory');
} else {
log.debug('inside FileUploadService ::: uploadFile >> Directory created');
}
//Write object on file system
fstream = nodefs.createWriteStream(filePath);
file.pipe(fstream);
fstream.on('close', function (err) {
if (!err) {
var relativePath = "/" + folderGuid + "/" + fileName;
log.info('Successfully uploaded file relativePath >> '+relativePath);
res.status(constants.HTTP_CODE_OK);
res.json({"relativePath": relativePath});
} else {
log.error({err: err}, 'Failed to upload file');
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
});
});
};
我知道下面的代码行会抛出错误,这是因为在多个文件的情况下,这行代码会执行两次导致错误。
res.status(constants.HTTP_CODE_OK);
res.json({"relativePath": relativePath});
如何跟踪“ req.busboy.on('file', function (fieldName, file, fileName)
”的多个事件,以便在所有文件处理完成后只有我应该发送响应?
请帮忙。