获取firebase数据库上的数据以替换字符串

时间:2017-05-03 11:37:25

标签: javascript angularjs node.js firebase firebase-realtime-database

当我运行此函数以从firebase数据库获取数据时

app.listen(3000)
app.engine('html', require('ejs').renderFile)
var bodyParser = require('body-parser');
var sm = require('sitemap')

var firebase = require('firebase').initializeApp({
    apiKey: "xx",
    authDomain: "xx.firebaseapp.com",
    databaseURL: "https://xx.firebaseio.com",
    projectId: "xx",
    storageBucket: "xx.appspot.com",
    messagingSenderId: "xx"
  });

database = firebase.database();
var ref = database.ref('urls');
ref.on('value', gotData, errData);

function errData(err){
    console.log('Error!');
    console.log(err);
}

function gotData(data){
    var url_sitemap = data.val();
    var keys = Object.keys(url_sitemap);
    console.log(keys);
}

结果

[ 'key1', 'key2', 'key3', 'key4' ]

我需要在此页面添加数据-xx /'在下面

var sitemap = sm.createSitemap({ 
    hostname: 'xxx.com',
    urls: [
        { url: '/page-xx/},
        { url: '/page-xx/},
        { url: '/page-xx/},
        { url: '/page-xx/}
    ]
});

如何将/ page-xx /替换为数据库中的数据?

1 个答案:

答案 0 :(得分:0)

这样的事情,使用ES6

const sitemap = sm.createSitemap({ 
    hostname: 'xxx.com',
    urls: gotData(data)
});

function gotData(data){
    const url_sitemap = data.val();
    const urls = [];
    Object.keys(url_sitemap)
          .forEach(k => urls.push({url: k }));
    return urls;
}

ES6

function gotData(data){
    var url_sitemap = data.val();
    var urls = [];
    var urlKeys = Object.keys(url_sitemap);
    for (var i = 0; i < urlKeys.length; i++) {
      urls.push({url: urlKeys[i] });
    }
    return urls;
}

var urls = gotData(/*-- your data -- */);

var sitemap = sm.createSitemap({
    hostname: 'xxx.com',
    urls: urls
});

注意:如果您正在进行异步调用以获取此数据,则可能需要将其包含在Promisecallback中。

更新

// store urls:
var urls = [];    

ref.on('value', gotData, errData);

function errData(err){
    console.log('Error!');
    console.log(err);
}

function gotData(data){
    var url_sitemap = data.val();
    var urlKeys = Object.keys(url_sitemap);
    for (var i = 0; i < urlKeys.length; i++) {
      urls.push({url: urlKeys[i] });
    }
}

var sitemap = sm.createSitemap({
    hostname: 'xxx.com',
    urls: urls
});