Basic example using NodeJS Streams.
Git clone this repository:
git clone https://github.com/Guilospanck/node-js-streams.git
Change directory into the repository:
cd node-js-streams/
Then run:
yarn
To install dependencies and then run:
yarn start:dev
Be sure to have Docker and Docker Compose installed.
Change directory into the repository:
cd node-js-streams/
Then run:
sudo docker-compose -f docker-compose.yml up -d --build
In order to view the logs once it's built, run:
sudo docker ps # get the id of the container
sudo docker logs [id]
Basically we have three main structures: Readable
, Transform
and Writable
.
The Readable is the source
of data. So, let's say we have a client-server
architecture and we, the client, want to retrieve some information from the server.
The Readable will be kept in the server and it will read and send the stream of data.
The Transform is the man in the middle
. It's responsible for making changes on the data. Everything you want to do with the stream of data, you can use the Transform to do that.
The Writable usually lies in the client and is responsive to finally do something with the data received.
Chunk
is the data coming from the stream. It is a buffer and if you want to get the data, just parse it usingJSON.parse(chunk);
or usetoString();
.Callback
is used to inform the server (the readable stream) that the client received the data and it can send the other. If we don't pass it, it won't get the next data.
Install TS dev dependencies:
yarn add -D typescript ts-node
Then generate a new tsconfig.json
file:
npx tsc --init
Use the tsconfig.json
that exists in this repository for a more complete version.
Also, add a new file called nodemon.json
in order to run Nodemon with TypeScript without getting an error.
Install the Jest dev dependencies:
yarn add -D jest ts-jest @types/jest
Then generate a new jest.config.js
(or jest.config.cjs
) file:
npx ts-jest config:init