Search code examples
javascriptnode.jsdom-eventseventemitter

Create custom event in node js and update custome obj


I've node app which listen to some events, I want to create my custom events which will update some object with property from this event, how its recommended to do that?

Lets say I've two files one with this following events (regular event) and

this is first.js

   //On open
    child.on('open', function (code) {
       //here raise my custom event with open property to the customObject
    });

    child.stdout.on('data', function (data) {
        //here raise my event with data property to the object
    });

    child.on('close', function (code) {
      //here raise my event with close property to the object
    });

    child.on('error', function (error) {
     //here raise my event with err property to the object
    });

In the second file second.js I want to update this custom object with value from the first file/module

second.js

var customObj ={
  data:false,
  open:true,
  close:true,
  error:error
}

Solution

  • In second.js, export a method like:

    exports.updateData = function updateData(data) {
      customObj.data = data; // or whatever
    }
    

    Then call this method in first.js event listener with the appropriate argument:

    var second = require("second.js");
    child.stdout.on('data', function (data) {
      second.updateData(data);
    });