I am using busboy module to upload files. It works very well for one file. However it throws following error when I tried to upload the multiple file.
Error: Can't set headers after they are sent
I know why its throwing error, but I am not able to figure out the solution. Following is my code snippet.
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});
}
});
});
});
};
I know following line of code is throwing error, this is because in case of multiple files, this line of code is executed twice which cause the error.
res.status(constants.HTTP_CODE_OK);
res.json({"relativePath": relativePath});
How can I track multiple event of "req.busboy.on('file', function (fieldName, file, fileName)
" so that once all file processing is finished then only I should send the response?
Please help.