Create a backend in Javascript (part 7): NodeJS Events and Streams
Tags: javascript, node, beginners, tutorial
Published: 2021-10-18 14:18:20

---
title: Create a backend in Javascript (part 7): NodeJS Events and Streams
published: true
description: 
tags: javascript, nodejs, beginner, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ph7yc1i1vqqgwpxegw5.png
series: nodejs
---

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_
<hr>

## 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

```jsx
const EventEmitter = require('events');

const myEmitter = new EventEmitter()

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

myEmitter.emit('newSale')
```

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

```jsx
console.log('A new sale occur')
```

### Pass arguments to listeners

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

```jsx
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)
```

### 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.

```jsx
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')
})
```

## 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.
```jsx
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);
})
```

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).