Reputation: 3
module.exports.upload = function (req, res) {
fileName = path.basename(req.query.fileName);
var fileExtn = path.extname(req.query.fileName);
console.log("fileName " + fileName);
console.log("fileExtn " + fileExtn);
var fileCheckResponse = FileCheck(req, res); // FileCheck method containing Busboy code
console.log("file check response =" + fileCheckResponse);
}
function FileCheck(req, res) {
var dataSize;
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
file.on("data", function (data) {
dataSize=data.length;
console.log("File [" + fieldname + "] got " + data.length + " bytes");
console.log("the upload file data ===== " + data);
})
});
busboy.on('finish', function() {
console.log('Upload complete');
return dataSize;
});
return req.pipe(busboy);
}`
here from upload method i am calling FileCheck function where Busboy code is present and i put debug and check in FileCheck function first it hits the line ( busboy.on('file', function(fieldname, file, filename, encoding, mimetype) ) then it doesn't goes inside it hits another line ( busboy.on('finish', function()) then response object goes back to upload method, i am expecting datalenght in fileCheckResponse but getting object which is not containing it, again on continue debug again it goes back to FileCheck function and this time it hits ( file.on("data", function (data)) and prints data on console as i have written but response doesn't comes back to upload method.
Here again my question and goal is to get datalength as response but now first time i am getting object as response and second time pointer doesn't come back to upload method.
Upvotes: 0
Views: 1278
Reputation: 26
// try using const or let instead of var
module.exports.upload = function (req, res) {
fileName = path.basename(req.query.fileName);
const fileExtn = path.extname(req.query.fileName)
console.log("fileName " + fileName);
console.log("fileExtn " + fileExtn);
// try to make FileCheck function synchronous using promise or async await
FileCheck(req, res)
.then(fileSize => {
console.log(fileSize, 'fileSize')
// send whatever response you need
})
}
function FileCheck(req, res) {
return new Promise((resolve, reject) => {
let dataSize;
let busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
file.on('data', function (data) {
dataSize = data.length;
console.log("File [" + fieldname + "] got " + data.length + " bytes");
})
});
busboy.on('finish', function() {
console.log('Upload complete');
resolve(dataSize)
});
req.pipe(busboy)
})
}
Upvotes: 1