Skip to content

Commit

Permalink
Add solutions for news exercices
Browse files Browse the repository at this point in the history
  • Loading branch information
fedekrenn committed Dec 13, 2023
1 parent f9fb303 commit 7c146d4
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 83 deletions.
1 change: 0 additions & 1 deletion live-coding/01-node-callbacks-promises/input.txt

This file was deleted.

1 change: 0 additions & 1 deletion live-coding/01-node-callbacks-promises/input2.txt

This file was deleted.

1 change: 0 additions & 1 deletion live-coding/01-node-callbacks-promises/output.txt

This file was deleted.

1 change: 0 additions & 1 deletion live-coding/01-node-callbacks-promises/output2.txt

This file was deleted.

4 changes: 3 additions & 1 deletion live-coding/01-node-callbacks-promises/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
"test": "tests"
},
"scripts": {
"test": "node --test"
"test": "echo \"Please use pnpm test1 or pnpm test2\"",
"test1": "node tests/index.test.js",
"test2": "node tests/dotenv.test.js"
},
"keywords": [],
"author": "Federico Krenn",
Expand Down
38 changes: 27 additions & 11 deletions live-coding/01-node-callbacks-promises/solutions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import net from 'node:net'
import fs from 'node:fs'
import { readFile, writeFile } from 'node:fs/promises'

export const ping = (ip, callbk) => {
export const ping = (ip, callbk) => { // Se agrega el cllbk como parámetro
const startTime = process.hrtime()

const client = net.connect({ port: 80, host: ip }, () => {
client.end()
callbk(null, { time: process.hrtime(startTime), ip })
callbk(null, { time: process.hrtime(startTime), ip }) // se cambia el return por el callbk
})

client.on('error', (err) => {
Expand Down Expand Up @@ -43,25 +43,25 @@ obtenerDatosPromise({ time: 1 })
*/

export function procesarArchivo (callbk) {
const handleWrite = error => {
const handleRead = (error, contenido) => {
if (error) {
console.error('Error guardando archivo:', error.message)
console.error('Error leyendo archivo:', error.message)
callbk(error)
}

console.log('Archivo procesado y guardado con éxito')
callbk(null)
const textoProcesado = contenido.toUpperCase()

fs.writeFile('output.txt', textoProcesado, handleWrite)
}

const handleRead = (error, contenido) => {
const handleWrite = error => {
if (error) {
console.error('Error leyendo archivo:', error.message)
console.error('Error guardando archivo:', error.message)
callbk(error)
}

const textoProcesado = contenido.toUpperCase()

fs.writeFile('output.txt', textoProcesado, handleWrite)
console.log('Archivo procesado y guardado con éxito')
callbk(null)
}

fs.readFile('input.txt', 'utf8', handleRead)
Expand All @@ -72,3 +72,19 @@ export async function procesarArchivoPromise () {
const textoProcesado = contenido.toUpperCase()
await writeFile('output2.txt', textoProcesado)
}

export async function leerArchivos () {
const data = await Promise.all([ // Se podría usar all o allSettled, pero allSettled es más seguro porque no falla si uno de los archivos no existe
readFile('archivo1.txt', 'utf8'),
readFile('archivo2.txt', 'utf8'),
readFile('archivo3.txt', 'utf8')
])

return data.join(' ')
}

export async function delay (time) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
114 changes: 57 additions & 57 deletions live-coding/01-node-callbacks-promises/tests/dotenv.test.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,57 @@
import { describe, it, beforeEach, afterEach } from 'node:test'
import { equal } from 'node:assert/strict'
import { unlinkSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { config } from '../solutions/dotenv.js'

describe('1. dotenv', () => {
beforeEach(() => {
// clean process.env
for (const key of Object.keys(process.env)) {
delete process.env[key]
}
})

afterEach(() => {
try {
unlinkSync('.env')
} catch {}

try {
unlinkSync('./test/.env.local')
} catch {}
})

it('1.1. load .env file', () => {
// create .env file in root directory
writeFileSync('.env', 'PORT=3000\nTOKEN="123abc"')
config()

equal(process.env.PORT, '3000')
equal(process.env.TOKEN, '123abc')
})

it('1.2. load .env file from custom path', () => {
// create .env file in root directory
writeFileSync('./test/.env.local', 'PORT=3000\nTOKEN="123abc"')
config({ path: './test/.env.local' })

equal(process.env.PORT, '3000')
equal(process.env.TOKEN, '123abc')
})

it('1.3 it works even without .env file', () => {
config()
equal(process.env.TOKEN, undefined)
})

it('1.4 dont use dotenv dependency', () => {
// check that dotenv dependency is not installed
try {
const require = createRequire(import.meta.url)
require('dotenv')
} catch (error) {
equal(error.code, 'MODULE_NOT_FOUND')
}
})
})
// import { describe, it, beforeEach, afterEach } from 'node:test'
// import { equal } from 'node:assert/strict'
// import { unlinkSync, writeFileSync } from 'node:fs'
// import { createRequire } from 'node:module'
// import { config } from '../solutions/dotenv.js'

// describe('1. dotenv', () => {
// beforeEach(() => {
// // clean process.env
// for (const key of Object.keys(process.env)) {
// delete process.env[key]
// }
// })

// afterEach(() => {
// try {
// unlinkSync('.env')
// } catch {}

// try {
// unlinkSync('./test/.env.local')
// } catch {}
// })

// it('1.1. load .env file', () => {
// // create .env file in root directory
// writeFileSync('.env', 'PORT=3000\nTOKEN="123abc"')
// config()

// equal(process.env.PORT, '3000')
// equal(process.env.TOKEN, '123abc')
// })

// it('1.2. load .env file from custom path', () => {
// // create .env file in root directory
// writeFileSync('./test/.env.local', 'PORT=3000\nTOKEN="123abc"')
// config({ path: './test/.env.local' })

// equal(process.env.PORT, '3000')
// equal(process.env.TOKEN, '123abc')
// })

// it('1.3 it works even without .env file', () => {
// config()
// equal(process.env.TOKEN, undefined)
// })

// it('1.4 dont use dotenv dependency', () => {
// // check that dotenv dependency is not installed
// try {
// const require = createRequire(import.meta.url)
// require('dotenv')
// } catch (error) {
// equal(error.code, 'MODULE_NOT_FOUND')
// }
// })
// })
37 changes: 27 additions & 10 deletions live-coding/01-node-callbacks-promises/tests/index.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { ping, obtenerDatosPromise, procesarArchivo, procesarArchivoPromise } from '../solutions/index.js'
import { describe, it, beforeEach, afterEach } from 'node:test'
import { ping, obtenerDatosPromise, procesarArchivo, procesarArchivoPromise, leerArchivos, delay } from '../solutions/index.js'
import { describe, it, afterEach } from 'node:test'
import { equal, ifError } from 'node:assert/strict'
import { unlinkSync, writeFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'

describe('1. ping', () => {
it('1.1. ping midu.dev', (_, done) => {
Expand All @@ -26,6 +25,9 @@ describe('3. procesarArchivoPromise', () => {
afterEach(() => {
try {
unlinkSync('output.txt')
unlinkSync('output2.txt')
unlinkSync('input.txt')
unlinkSync('input2.txt')
} catch {}
})

Expand All @@ -48,16 +50,31 @@ describe('3. procesarArchivoPromise', () => {
equal(contenido, 'HOLA')
})
})
/*
describe('4. leerArchivos', () => {
// it('4.1. leerArchivos', () => {
// const mensaje = leerArchivos()
// equal(mensaje, 'hola qué tal')
// })

describe('4. leerArchivos', () => {
afterEach(() => {
try {
unlinkSync('archivo1.txt')
unlinkSync('archivo2.txt')
unlinkSync('archivo3.txt')
} catch {}
})
it('4.1. leerArchivos', async () => {
writeFileSync('archivo1.txt', 'hola')
writeFileSync('archivo2.txt', 'qué')
writeFileSync('archivo3.txt', 'tal')
const mensaje = await leerArchivos()
equal(mensaje, 'hola qué tal')
})
})
*/

describe('5. delay', () => {
it('5.1. delay', async () => {
const timeToDelay = 1000
const start = Date.now()
await delay(timeToDelay)
const end = Date.now()
const diff = end - start
equal(diff >= timeToDelay, true, 'La función delay debería retrasar la ejecución al menos 1000ms')
})
})

0 comments on commit 7c146d4

Please sign in to comment.