Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
davidalves1 committed Jan 4, 2023
0 parents commit 286be51
Show file tree
Hide file tree
Showing 6 changed files with 402 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# http://editorconfig.org
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 120

[*.md]
max_line_length = 0
trim_trailing_whitespace = false

[COMMIT_EDITMSG]
max_line_length = 0
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
17 changes: 17 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "node-streams",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"type": "module",
"scripts": {
"client": "nodemon src/client.js",
"server": "nodemon src/server.js"
},
"devDependencies": {
"nodemon": "^2.0.20"
},
"dependencies": {
"axios": "^1.2.2"
}
}
46 changes: 46 additions & 0 deletions src/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import axios from 'axios'
import { Transform, Writable } from 'stream'

const url = 'http://localhost:3300'

async function consume() {
const response = await axios({
url,
method: 'GET',
responseType: 'stream',
})

return response.data
}

const stream = await consume()

stream
.pipe(
new Transform({
// Não é legal usar esta função como async, pois pode fechar
// a stream sem ter terminado o processamento
// - chunk é o pedaço recebido pela stream
transform(chunk, enc, cb) {
// Como o server manda o json como resposta é preciso fazer o parser dele
const item = JSON.parse(chunk)
const { name } = item

const itemNumber = /\d+/.exec(name)[0]

item.name = (itemNumber % 2 === 0) ? `${name} é par` : `${name} é ímpar`

// o callback informa o fim do processo
cb(null, JSON.stringify(item))
}
})
)
.pipe(
new Writable({
write(chunk, enc, cb) {
console.info('The End', chunk.toString())

cb()
}
})
)
42 changes: 42 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import http from 'http'
import { Readable } from 'stream'
import { randomUUID } from 'crypto'

const PORT = process.env.PORT || 3300

// Generator
function* run() {
for(let i = 0; i < 100; i++) {
const data = {
id: randomUUID(),
name: `David-${i}`,
}

// Retorna o dado que já foi processado mesmo antes do loop terminar
yield data
}
}

async function handler(request, response) {
const readable = new Readable({
read() {
for (const data of run()) {
console.log('🚀 ~ sending', data);
// Transforma em string pois as streams só trabalham com este tipo de dado
// por causa do buffer
this.push(JSON.stringify(data) + "\n");
}

// Informa que os dados acabaram
this.push(null)
}
})

readable
// O pipe vai gerenciar o dado recebido
.pipe(response)
}

http.createServer(handler)
.listen(PORT)
.on('listening', () => console.info(`listening on localhost:${PORT}`))
Loading

0 comments on commit 286be51

Please sign in to comment.