Q:

unable to return variable in node.js

i'm returning the variable uploadFile from my function and when I'm trying to access it in another variable it gives me undefined
function upload(req, res, callback) {
    var dir = 'uploads/';

    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }

    console.log(req.files.file1);
    console.log(req.files.file2);

    var uploadFiles = {
        ext1: path.extname(req.files.file1.originalname),
        path1: req.files.file1.path,
        ext2: path.extname(req.files.file2.originalname),
        path2: req.files.file2.path
    }
    return callback(uploadFiles);
}

this is the function where I'm calling the upload function I guess I'm doing it the wrong way, I'm getting Callback is not a function as the error ... please guide me  
function sendMail(req, res) {
    var data = req.body;
     upload(req,res);
// checking the condition if the file has been uploaded
    if (uploadFiles) {
        data_to_send.attachments = [{
            filename: 'file1' + uploadFiles.file1ext,
            filePath: uploadFiles.file1Path 
        }, {
            filename: 'file2' + uploadFiles.file2ext,
            filePath: uploadFiles.file2Path
        }]
    }
    console.log(data_to_send.attachments)
    smtpTransport.sendMail({
            from: data_to_send.from,
            to: data_to_send.to,
            subject: data_to_send.subject,
            atachments: data_to_send.attachments,
            text: data_to_send.text,
            html: data_to_send.html
        },
//.........

A:

The problem is that in your upload function you are not checking that callback was actually passed (and not undefined). Also, you are not returning your values, you are actually returning whatever callback is returning.
Here is some code that might help you:
// inside your upload function
var uploadFiles = {
        ext1: path.extname(req.files.file1.originalname),
        path1: req.files.file1.path,
        ext2: path.extname(req.files.file2.originalname),
        path2: req.files.file2.path
    }
if (callback) {
    callback(uploadFiles);
}

//inside your sendMail (notice the 3rd parameter passed to upload)
upload(req, res, function (uploadFiles) {
    if (uploadFiles) {
        data_to_send.attachments = [{
            filename: 'file1' + uploadFiles.file1ext,
            filePath: uploadFiles.file1Path 
        }, {
            filename: 'file2' + uploadFiles.file2ext,
            filePath: uploadFiles.file2Path
        }]
    }
    // rest of the code goes here, inside the callback.
});

Now you will actually receive your files in the callback, as you wanted.

