Lujska Lujska - 5 months ago 125
Node.js Question

How to get and set data to Firebase with Node.js?

I'm learning Firebase and Node.js. I want get my Tweets from Twitter and send them to Firebase. I have no problem to get tweet from Twitter. My question is how can I send data to Firebase?

I tried the following code:

var firebase = require('firebase');

// Initialize
var app = firebase.initializeApp({
ServiceAccount: {
projectId: "******",
clientEmail: "****@gmail.com",
privateKey: "-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----\n"
},
databaseURL: "****.firebaseio.com"
});

// Set Sample Data
firebase.database().ref('/').set({
username: "test",
email: "test@mail.com"
});


And I got the following error on console:

Debugger listening on port 5858
crypto.js:279
var ret = this._handle.sign(toBuf(key), null, passphrase);
^

Error: error:0906D064:PEM routines:PEM_read_bio:bad base64 decode
at Error (native)
at Sign.sign (crypto.js:279:26)
at Object.sign (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\node_modules\jws\node_modules\jwa\index.js:54:45)
at Object.jwsSign [as sign] (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\node_modules\jws\lib\sign-stream.js:23:24)
at Object.JWT.sign (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\index.js:137:16)
at authJwt (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:83:16)
at fetchAccessToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:96:17)
at app_.INTERNAL.getToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:196:14)
at Zb.getToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\database-node.js:28:3496)
at yh (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\database-node.js:195:334)
Press any key to continue...


Also, this my firebase Rules: {"rules":{".read":true,".write":true}}

Answer

I solved my problem. I just downloaded serviceAccount json file from Firebase Console and inserted it to my project. The 'Service Account' file contains everything that you need.

var firebase = require('firebase');

firebase.initializeApp({
    databaseURL: 'https://*****.firebaseio.com',
    serviceAccount: 'myapp-13ad200fc320.json', //this is file that I downloaded from Firebase Console
});

Then the code below worked nicely.

Firebase.database().ref('/').set({
    username: "test",
    email: "test@mail.com"
});