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 the…


This content originally appeared on DEV Community and was authored by Eric The Coder

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

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

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)

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

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);
})

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


This content originally appeared on DEV Community and was authored by Eric The Coder


Print Share Comment Cite Upload Translate Updates
APA

Eric The Coder | Sciencx (2021-10-18T14:18:20+00:00) Create a backend in Javascript (part 7): NodeJS Events and Streams. Retrieved from https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/

MLA
" » Create a backend in Javascript (part 7): NodeJS Events and Streams." Eric The Coder | Sciencx - Monday October 18, 2021, https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/
HARVARD
Eric The Coder | Sciencx Monday October 18, 2021 » Create a backend in Javascript (part 7): NodeJS Events and Streams., viewed ,<https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/>
VANCOUVER
Eric The Coder | Sciencx - » Create a backend in Javascript (part 7): NodeJS Events and Streams. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/
CHICAGO
" » Create a backend in Javascript (part 7): NodeJS Events and Streams." Eric The Coder | Sciencx - Accessed . https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/
IEEE
" » Create a backend in Javascript (part 7): NodeJS Events and Streams." Eric The Coder | Sciencx [Online]. Available: https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/. [Accessed: ]
rf:citation
» Create a backend in Javascript (part 7): NodeJS Events and Streams | Eric The Coder | Sciencx | https://www.scien.cx/2021/10/18/create-a-backend-in-javascript-part-7-nodejs-events-and-streams/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.