
How To Build An NPM Module?
So,first comes learning about events in Nodejs.
- How to create events
- How to handle events
The knowledge of both is important.I’m assuming you already have some experience with front-end coding — everyone begins from there.
Having done front-end coding,you obviously did come across “mouse events”,”keyboard events” and most importantly “the click event” implemented using the .onclick() method.
Now,when dealing with events in Nodejs,its pretty much like how you did it in front-end.
Deconstructing An Event
The most noticeable part is the eventName and a callback function attached to it.
Anything is best understood with examples-that would aid you in visualizing the theoretical explanations of what goes on under the hood:
To implement this example:
npm install socket.io
Thats all we need.
Two methods are required.
.emit() and .on()
The .on() will handle event and .emit() calls for the event,when it does this,the execution transfers to the particular .on() method thats handling the event we will be dealing with inside .emit() .
socket.emit(“msg”,text);
socket.on(“msg”,function(text){
//code to handle the variable text
});
More on events and building an npm module in the next part.
