NodeJS by Example: Write Streams
|
Write Streams allow you to write data to a destination piece by piece, rather than writing everything at once. This is essential for handling large amounts of data efficiently. |
|
|
Import the required modules for working with write streams. |
|
|
Creating a Write Stream createWriteStream opens a file for writing and returns a writable stream. |
|
|
Writing Data The write() method writes data to the stream. It returns true if the internal buffer is below the highWaterMark, false if you should wait. |
|
|
Ending the Stream The end() method signals that no more data will be written. You can optionally write final data. |
|
|
Stream Events Write streams emit events you should handle: 'finish', 'error', 'drain', 'close'. |
|
|
Handling Backpressure When write() returns false, the internal buffer is full. Wait for 'drain' before writing more. |
|
|
Writing Different Data Types You can write strings, Buffers, or Uint8Arrays. Write a string Write a Buffer Write with callback |
|
|
Stream Options createWriteStream accepts several useful options. |
|
|
Creating Custom Writable Streams You can create custom writable streams by extending Writable or using the constructor. |
|
|
Writing to Standard Output process.stdout is a writable stream. You can write to it directly. Check if stdout supports colors (TTY) |
|
|
Practical Example: CSV Writer A function that writes data rows to a CSV file efficiently. Usage example |
|
|
Run the write streams example |
|
|
Check the output files |
|