如何访问Node.js函数之外的变量数据?

时间:2014-09-15 09:03:33

标签: node.js function variables google-analytics

这是Node.js中的一个函数,它从Analytics中读取数据:

function getDataFromGA(Dimension, Metric, StartDate, EndDate, MaxResults) {
var fs = require('fs'),
    crypto = require('crypto'),
    request = require('request'); // This is an external module 

var authHeader = {
        'alg': 'RS256',
        'typ': 'JWT'
    },
    authClaimSet = {
        'iss': '***t@developer.gserviceaccount.com', // Service account email
        'scope': 'https://www.googleapis.com/auth/analytics.readonly',
// We MUST tell them we just want to read data
        'aud': 'https://accounts.google.com/o/oauth2/token'
    },
    SIGNATURE_ALGORITHM = '**',
    SIGNATURE_ENCODE_METHOD = '**',
    GA_KEY_PATH = '**',
  //finds current directory then appends  private key to the directory
    gaKey;

function urlEscape(source) {
    return source.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}

function base64Encode(obj) {
    var encoded = new Buffer(JSON.stringify(obj), 'utf8').toString('base64');
    return urlEscape(encoded);
}

function readPrivateKey() {
    if (!gaKey) {
        gaKey = fs.readFileSync(GA_KEY_PATH, 'utf8');
    }
    return gaKey;
}

var authorize = function (callback) {

    var self = this,
        now = parseInt(Date.now() / 1000, 10), // Google wants us to use seconds
        cipher,
        signatureInput,
        signatureKey = readPrivateKey(),
        signature,
        jwt;

    // Setup time values
    authClaimSet.iat = now;
    authClaimSet.exp = now + 60; // Token valid for one minute

    // Setup JWT source
    signatureInput = base64Encode(authHeader) + '.' + base64Encode(authClaimSet);

    // Generate JWT
    cipher = crypto.createSign('RSA-SHA256');
    cipher.update(signatureInput);
    signature = cipher.sign(signatureKey, 'base64');
    jwt = signatureInput + '.' + urlEscape(signature);

    // Send request to authorize this application
    request({
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        uri: 'https://accounts.google.com/o/oauth2/token',
        body: 'grant_type=' + escape('urn:ietf:params:oauth:grant-type:jwt-bearer') +
            '&assertion=' + jwt
    }, function (error, response, body) {
        if (error) {
            console.log(error);
            callback(new Error(error));
        } else {
            var gaResult = JSON.parse(body);
            if (gaResult.error) {
                callback(new Error(gaResult.error));
            } else {
                callback(null, gaResult.access_token);
            //    console.log(gaResult);
                console.log("Authorized");

            }
        }
    });

};

var request = require('request'),
    qs = require('querystring');

authorize(function (err, token) {
    if (!err) {
        // Query the number of total visits for a month

        var requestConfig = {
            'ids': 'ga:72333024',
            'dimensions': Dimension,
            'metrics': Metric,
            // 'sort': '-ga:users',
            'start-date': StartDate,
            'end-date': EndDate,
            'max-results': MaxResults
        };

        request({
            method: 'GET',
            headers: {
                'Authorization': 'Bearer ' + token // Here is where we use the auth token
            },
            uri: 'https://www.googleapis.com/analytics/v3/data/ga?' + qs.stringify(requestConfig)
        }, function (error, resp, body) {
            console.log(body);
            var data = JSON.parse(body);
            console.log(data.totalsForAllResults);
            console.log(data.rows);
        });
    }
});
}

我试着从外面访问它:

var gaJSON = utils.getDataFromGA("ga:country", "ga:pageviews", "2011-08-04", "2014-09-12", "50");
res.send(gaJSON);

我的问题是如何在第一个方法的末尾访问变量data?如何从函数外部调用它?

2 个答案:

答案 0 :(得分:0)

您可以将数据分配给第一个函数中声明的变量。但由于authorize方法是异步的,因此在第一个函数结束时仍然不会定义变量数据。执行此操作的最佳方法是使用回调处理。

我想你想要回复与这个变量有关的东西,对吧?尝试将回调参数放到第一个函数中,然后调用此函数传递结果。

callback(variable)

答案 1 :(得分:-1)

为什么要从外面访问。 ?? 即使你想要拼命,然后你需要创建一个函数传递"数据"作为参数然后调用函数。

console.log(body);
var data = JSON.parse(body);
myNewFunction(data);

将所有你的逻辑写在" myNewFunction"使用数据。