Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Implement a Node.Js server-side event listener for Firebase?

I'm trying to listen for data changes in my firebase using firebase's package for Node. I'm using the on() method which is supposed to listen for changes non-stop (as opposed to once() method that only listens to the first occurrence of a specific event ) My listener.js file on the server is exactly like this:

var Firebase=require('firebase');
var Ref= new Firebase('https://mydatabase.firebaseio.com/users/');
 Ref.on('child_changed',function(childsnapshot,prevchildname){
 Ref.child(childsnapshot.key()).push("I hear you!");

} ) ;

But it only works the for the first occurrence and throws a fatal memory error after a second occurrence.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I'm very new to server side programming and don't know what to do. I must be missing something important. Should I set up special server settings with node first? or maybe make a daemon that runs a script with once() method every second or so ?

like image 901
Dil manous Avatar asked Oct 19 '22 10:10

Dil manous


1 Answers

I'm pretty sure you're creating an endless loop here:

  1. You push a value to https://mydatabase.firebaseio.com/users/
  2. the on('child_changed' event fires in your script
  3. your script pushes a new child under the value
  4. so we go back to step 2 and repeat

It will happen quite rapidly too, since Firebase clients fire local events straight away.

It looks like you're trying to create a chat bot. Which means you more likely want to create sibling messages:

var Firebase=require('firebase');
var ref= new Firebase('https://mydatabase.firebaseio.com/users/');
ref.on('child_changed',function(childsnapshot,prevchildname){
  ref.push("I hear you!");
}) ;

Note that it is pretty inefficient to use StackOverflow to debug code. Since you seem to be on Windows, I recommend installing Visual Studio and its node tools. They have a great debugger that allows you to step through the code. Setting a breakpoint in your callback (so in the line with ref.push), will quickly show you what is going wrong.

like image 164
Frank van Puffelen Avatar answered Oct 22 '22 01:10

Frank van Puffelen