Stream and Buffers
Streams and buffers are two important concepts in Node.js for handling data in an efficient and scalable way.
A stream is a sequence of data chunks that can be read from or written to. Streams are useful for working with large amounts of data, such as reading data from a file or processing incoming network data, because they allow you to read or write data in small chunks, instead of loading the entire data into memory at once. In Node.js, streams can be either readable, writable, or both.
A buffer is a region of memory used to temporarily store data. Buffers in Node.js are similar to arrays, but have different memory management and can store binary data, not just strings. In Node.js, you can use buffers to store data that you read from or write to a stream.
Here's an example of how you could use streams and buffers to read data from a file:
In this example, the fs
module is used to create a readable stream for the file file.txt
. The data
event is emitted whenever a chunk of data is available to be read, and the end
event is emitted when the entire file has been read. In the event handler for the data
event, the chunk of data is logged to the console after being converted to a string using the toString()
method.
This is just a simple example of how you can use streams and buffers in Node.js.
Last updated