What is Firebase Realtime Database?
It is a NoSQL database by Google that lets you store and access data in realtime.
Note:
All Firebase Realtime Database data is stored as JSON objects.
What is REPL, CLI and Node.js?
Click here to check out the blog post where I have explained them in detail.
Steps to perform on Firebase
Sign in to your Google account, go to Firebase console and click on
Add Project
Give a name to your project, uncheck "Enable Google Analytics for this project" if you do not wish to enable analytics for the project and click on continue to create the project.
That will generate your app's Firebase configuration which we will need in our project. Copy it for later use.
Proceed to the console, select "Realtime Database" and click "Create Database"
Select "Start in test mode" and click "Enable".
Read the security rules of realtime database and secure your app accordingly. For the purpose of this tutorial, we will just go ahead with test mode.
Steps to implement Firebase in your app
- Include firebase package in your Node.js app ```javascript
var firebase = require('firebase')
2. Paste the Firebase configuration that you copied earlier. I have shown an empty config for your reference here:
```javascript
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
}
- Initialize your Firebase app: ```javascript
firebase.initializeApp(firebaseConfig)
4. Get a reference to the database service:
```javascript
let database = firebase.database()
Firebase is now configured with our app.
How to write data to firebase?
Create a reference to your custom path at which you want to write your JSON object (mentioned as "obj" in the snippet below).
Then you set that object on the path:
database.ref("customPath").set(obj, function(error) {
if (error) {
// The write failed...
console.log("Failed with error: " + error)
} else {
// The write was successful...
console.log("success")
}
})
How to read data from firebase?
Create a reference to your custom path at which the data was written. Then you read the value at that path:
database.ref('customPath').once('value')
.then(function(snapshot) {
console.log( snapshot.val() )
})
You can either read the data once or continously read the data at a path and listen for changes. For more details, check out their documentation
Top comments (1)
your blog saved my time today! thanks