无法在node.js中返回变量

时间:2016-04-23 08:17:47

标签: 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);

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

2 个答案:

答案 0 :(得分:2)

问题在于,在您的上传功能中,您没有检查回调是否实际传递(并且未定义)。此外,您没有返回您的值,您实际上正在返回任何回调的返回值。

以下是一些可能对您有所帮助的代码:

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

现在,您将实际收到回调中的文件,如您所愿。

答案 1 :(得分:-2)

这是一个范围问题。您无法在另一个函数中调用uploadFiles,因为您是在上传中定义它。您可以尝试在上传之外定义它,或者您可以尝试控制台(上传(您传入的参数))。方案三,我完全误解了你的要求。

以下是Javascript中作用域的一个很好的参考: What is the scope of variables in Javascript?