Javascript 无法在node.js中返回变量
我从函数返回变量uploadFile,当我试图在另一个变量中访问它时,它会给我未定义的变量Javascript 无法在node.js中返回变量,javascript,node.js,Javascript,Node.js,我从函数返回变量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); v
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);
}
这是我调用上传函数的函数
我想我做得不对,我得到的回调不是函数
,因为错误。。。请引导我
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
},
//.........
这是一个范围问题。您不能在另一个函数中调用uploadFiles,因为您正在upload中定义它。您可以尝试在upload之外定义它,也可以尝试控制台(upload(您正在传递的参数))。选项三,我完全误解了你的要求 下面是Javascript中作用域的一个很好的参考:
问题在于,在上载函数中,您没有检查回调是否已实际传递(且未定义)。另外,您并没有返回您的值,您实际上返回的是回调返回的任何内容 以下是一些可能对您有所帮助的代码:
// 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.
});
现在,您将在回调中收到您想要的文件。这有助于您在遇到异常时,尝试将整个函数包装在try/catch中,看看是否有任何内容被捕获。看起来您不应该未定义。如何获取值并使用它?即使我在另一个函数中使用console(uploadFiles),我也没有定义。你能告诉我们你是如何调用upload的吗?误解,他没有访问变量,他正在访问返回的数据(在这种情况下是uploadFiles变量)…谢谢,这很有帮助,我真的需要学习更多关于编码和javascript的知识。你能邀请我聊天吗?这样我可以从你那里学到更多