DEV Community

Cover image for Create a backend in Javascript (part 7): NodeJS Events and Streams
Eric The Coder
Eric The Coder

Posted on

Create a backend in Javascript (part 7): NodeJS Events and Streams

Here is a series of articles to help you create backend applications in Javascript.

Node.js is now a must, so it is essential for a developer to master it.

I will publish a new article every two days and little by little you will learn everything there is to know about Node.js

To not miss anything follow me on twitter: https://twitter.com/EricTheCoder_


Events

Much of the Node.js kernel is built around an idiomatic event-driven asynchronous architecture in which certain types of objects (called "emitters") emit events that cause a "listeners" function call.

The following example shows a simple EventEmitter with a single "listener" that occurs when, for example, a sale is made

const EventEmitter = require('events');

const myEmitter = new EventEmitter()

myEmitter.on('newSale', () => {
  console.log('A new sale occur')
})

myEmitter.emit('newSale')
Enter fullscreen mode Exit fullscreen mode

The eventEmitter.on() method is used to register a "listeners", while the eventEmitter.emit() method is used to trigger the event.

When the event is triggered, the content of the function callback will be executed

console.log('A new sale occur')
Enter fullscreen mode Exit fullscreen mode

Pass arguments to listeners

The eventEmitter.emit () method allows an arbitrary set of arguments to be passed to "listeners" functions

const EventEmitter = require('events');

const myEmitter = new EventEmitter()

myEmitter.on('newSale', (total) => {
  console.log(`A new sale occur total of: ${price}`)
})

myEmitter.emit('newSale', 599.99)
Enter fullscreen mode Exit fullscreen mode

Node.js server works with an eventEmitter

Now that we know about Node.js events. We are able to better understand the logic of the Node.js server object.

const server = http.createServer()

// Create an event called "request"
server.on('request', (req, res) => {
  // Execute this code when the "request" event is trigger
  res.end('Request received')
})

// this will loop and wait for events
server.listen(5000, '127.0.0.1', () => {
  console.log('Waiting for request')
})
Enter fullscreen mode Exit fullscreen mode

Streams

What are Streams?

Streams are used to process (read and write) data piece by piece (chunks) without completing the entire read and write operation and also without keeping all the data in memory.

Youtube or Netflix are good examples of Streams. You don't need to wait for the video to fully load. The process is done piece by piece (chunks). So you can start watching the media even if the entire file is not yet downloaded.

In Node.js, there are "readable" Streams and "writable" Streams. Readable Streams can for example be a read file or an http request for data.

Writable Streams is the opposite of Readable Streams so for example an http response or a file to send

Here is an example of reading a large data file.

const fs = require('fs')
const server = require('http').createServer()

server.on('request', () => {
    // No need to load the entire file to memory
    // fs.readFile('data.txt', (err, data) => {
    //    if (err) console.log(err)
    //    res.end(data);
    // })

    // Create a Readable Streams
    const readable = fs.createReadStream('data.txt')

    // Pipe the Stream chunk to a writable Stream
    readable.pipe(res);
})
Enter fullscreen mode Exit fullscreen mode

The readable.pipe() method attaches a "writeable" Stream to the "readable", which automatically switches it to fluid mode and transfers all of its data to the attached "writable". The data stream will be automatically managed so that the destination "writable" Stream is not overwhelmed by a faster "readable" Stream.

Conclusion

That's all for today, follow me on twitter: https://twitter.com/EricTheCoder_ to be notified of the publication of the next article (within two days).

Top comments (3)

Collapse
 
salehmubashar profile image
Saleh Mubashar

thanks a lot eric, just what I needed to understand .
Although i have a lot of experience in React, but now
I know how to use it with Node too.
Would really appreciate if u check out my profile too, i got a few React related posts too
Once again thanks!

Collapse
 
guipinheiro profile image
Guilherme Pinheiro

Hello! Thanks for the content, Eric. Just what I was needing to start my backend journey.
Just one question. About the event example of using arguments, you use the parameter 'total' on the anonymous function, but when creating the output, you use 'price' as the variable on the template literal inside console.log(). It should be the same variable, right?

Thanks again!

Collapse
 
max10 profile image
max10

Thanks, I've just read all. very interesting and educational