I wrote a promise function in a firebase.js to return access key which I wanted to use everywhere after I start the server. But for some reason when I export the module and use it in app.js, I can't print the returned access_token Or a better question would be , how to use the access_token everywhere globally after the server is started.
Firebase.js is below
var {google} = require('googleapis');
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];
var http = require('http');
function getAccessToken() {
return new Promise(function(resolve, reject) {
var key = require('./serviceAccountKey.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
getAccessToken().then(function(access_token){
//console.log(access_token);
return access_token;
})
module.exports.getAccessToken = getAccessToken
Below is app.js
const express = require("express");
const ac = require('./firebase.js');
const app = express();
console.log(ac.getAccessToken);
const port = process.env.PORT || 1111 ;
app.listen(port, () => {
//console.log(`server up and running on ${process.env.PORT}`);
console.log(`server up and running on ` + port);
});
I start the server by nodemon index.js