journeykeron.blogg.se

Nodejs events
Nodejs events







The following is an example showing their usage: process.on("exit", () => console.log("Exit")) process.on("beforeExit", () => console.log("Before Exit")) process. These events are: process.on(‘exit’) process.on(‘uncaughtException’) The process object exposes some variables we can listen to and respond to accordingly. Every process action on the machine or a program is an event. The process.exit() method is the method that is used to end the Node.js process. In the data listener, the buffer gets printed instead of the string since NodeJS, instead of reading the text content of the file, actually reads the file as a buffer.Īnother example of NodeJS using event emitters is the global process variable. The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine. We don’t need to call the listeners explicitly as NodeJS internally extends event emitters, exposes custom predefined events ( data, open, end), and raises these events automatically when required for the streams. Depending on your application’s requirement, some events should only be handled once throughout the application lifecycle and can be achieved with the once. We can create an event source by creating new EventEmitter and then calling emit method. Notice here the listeners are called internally by NodeJS. As we did above, when a listener is registered using the emitter.on() method, that listener will be invoked every time the named event is emitted. We can capture events in NodeJS using events module. Chunk: 1 - Chunk: 2 - Chunk: 3 - Completed Reading.ĭata.txt is a large text file containing some random lorem-ipsum text These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

nodejs events

#NODEJS EVENTS CODE#

When executed, the code will give the following output: Started Reading.







Nodejs events