无法在node.js中返回variables

我从我的函数返回variablesuploadFile,当我试图访问它在另一个variables它给我不明确

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); } 

这是我打电话upload function我想我做错了方式,我越来越Callback is not a function作为错误…请指导我

 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 }, //......... 

问题是,在你的上传函数中,你没有检查callback是否真的被传递(而不是未定义)。 而且,你没有返回你的值,你实际上返回任何callback正在返回。

这里有一些代码可以帮助你:

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

现在,你会真正收到你的文件在callback,如你所愿。

这是一个范围问题。 您不能在另一个函数中调用uploadFiles,因为您正在上传中定义它。 你可以尝试在上传之外定义它,或者你可以尝试控制台(上传(你传入的参数))。 选项三,我完全误解你在问什么。

这里是一个很好的参考使用Javascript作用域: 什么是在Javascript中的variables的范围?