我从函数中返回变量 uploadFile,当我尝试在另一个变量中访问它时,它给了我未定义
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);
}
这是我调用上传函数
的函数,我想我做错了,我得到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
},
//.........
最佳答案
问题是,在您的上传函数中,您没有检查回调是否实际传递(并且不是未定义)。另外,您没有返回您的值,您实际上正在返回任何回调正在返回的内容。
下面是一些可能对您有帮助的代码:
// 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.
});
现在您将真正按照您的意愿在回调中收到文件。
关于javascript - 无法返回node.js中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808391/