2016-04-21 64 views
-4
"use strict"; 

var Tabletop = require("tabletop"); 
var base64 = require('base-64'); 


Tabletop.init({ key: 'xxxxxg46hgfjd', 
        callback: showInfo, 
        simpleSheet: true }) 

function showInfo(data, tabletop) { 
     console.log(data); 
     console.log(base64.encode(data)); 
} 

var vGlobals = { 
    dataString: base64.encode(data) 
}; 

module.exports = vGlobals; 

如何從showInfo訪問數據變量以便在vGlobals中使用?它說它尚未定義。變量優先級(節點js中的全局變量)

+0

你可以添加一個你如何使用它的例子嗎?不明白你在這裏做什麼。謝謝 – jaumard

+0

showinfo使它成爲json類型的文件。我想將它編碼爲64位。但是,showInfo中的變量數據與vGlobals中的變量數據不同。 –

回答

0

你的方法是錯誤的,你不能這樣做,因爲TableTop異步地調用你的回調函數。

我的建議(一個快速):

var dataString = null; 
    module.exports = function(cb) { 
     if (dataString == null) 
      Tabletop.init({ 
       key: 'xxxxxg46hgfjd', 
       callback: function(data, tabletop) { 
        dataString = base64.encode(data); 
        cb(dataString); 
       }, 
       simpleSheet: true 
      }); 
     else cb(dataString); 
    }; 

並獲取數據:

var dataManager = require('./myfile'); 
dataManager(function(dataString) { 
    //here is your data do what you want with it 
}) 

你應該看看/瞭解更多有關節點/ javascript和異步/事件驅動編程。

+0

問題是,當我使用這個模塊時,dataString仍然被視爲null,而不是像在函數中執行的base64.encode(data)。 :( –

+0

你什麼時候調用showInfo?因爲在你的示例中你不這樣dataString總是空的 – jaumard

+0

我把showInfo();在module.exports之前。 –