Saturday, September 5, 2020

custom event,modules and exports

custom event :

const events = require('events');

let emitter = new events.EventEmitter();//calling a constructor


emitter.on('newEvent',(message))=>{

 console.log(`Message: ${message}`);

});


emitter.emit('newEvent','Hello guys this is Uday Kiran');

--------------------

modules sample:

const fs = require('fs')

require('./utils.js')

const name1 = require('./utils1.js')

const add = require('./utils2.js')


fs.writeFileSync('notes.txt','My name is uday')

fs.appendFileSync('notes.txt','My name is kiran')

const name = 'asdsa'

console.log(name)

console.log(name1)


const sum = add(4,-2)

console.log(sum)



utils1.js

----

console.log('from utils1')

const fname = 'asdfr'


module.exports = fname


utils2.js

---

const add = function(q,b){

return q + b

}


module.exports = add


--------------------------------------------

Another sample:

 lib.js

---------

console.log(module);


module.exports.title = 'NODE';

module.exports.title2 = 'NODE3';

module.exports.cal = function(){

  console.log('sdfdf')

}


//console.log(module.expots);

//console.log(module.expots.title);

console.log(module.expots.cal());


//lib.js

//----

module.exports = {

  someProperty: 'somevalue',

  cal: function(val1,val2){

    return val1+val2;

  }

};


//main.js

//----

const object = require('./lib');

console.log(object.cal(100,233));

console.log(object.someProperty)


Divide above event  creation to modules:

modules\SendEmail.js

--

const events = require('events');

let emitter = new events.EventEmitter();

module.exports = emitter; 


emailevent.js

--

const emitter = require('./modules/SendEmail')

emitter.on('emailEvent',(message)=>{

  console.log(`Email: ${message}`);

});

emitter.emit('emailEvent','Send activation email to user after registration');



No comments:

Post a Comment