Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added .env
Empty file.
38 changes: 38 additions & 0 deletions lessons/custom-express/framework/Application.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const http = require('http')
const Emitter = require('events')
/**
* router = {
* [/getAllUsers]:[GET] : callback
* }
*/
module.exports = class Application {

constructor(){
this.router = []
this.server = http.createServer((req, res) => {
console.log('try to generate fake event....');
this.emitter.emit('[/getUsers]:[GET]', req, res)
})
this.emitter = new Emitter()
}

listen(port, callback){
return this.server.listen(port, callback)
}

addRouter(newRouter) {
this.router.push(newRouter)
}

initRoutes(){
this.router.forEach(router => {
const _router = router.endpointsMap

Object.keys(_router).forEach(maskEvent => {
console.log(_router);
this.emitter.on(maskEvent, _router[maskEvent])
})
})
}

}
6 changes: 6 additions & 0 deletions lessons/custom-express/framework/Router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = class Router {
constructor(endpointsMap) {
this.endpointsMap = endpointsMap
}

}
Empty file.
Empty file.
Empty file.
32 changes: 32 additions & 0 deletions lessons/custom-express/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { MongoClient, ServerApiVersion } = require('mongodb');
const userRouter = require('./src/user-router')
const Application = require('./framework/Application')

const PORT = 3000

const app = new Application()


app.addRouter(userRouter)

app.initRoutes()

const start = async () => {
await connectDB()
app.listen(PORT, () => console.log('Start server on port 3000'))
}



async function connectDB() {
const uri = "mongodb+srv://lormida:midapa24@cluster0.oien5qs.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });

try {
await client.connect()
console.log('Success connection...')
} catch (e) {
throw e
}
}
start()
9 changes: 9 additions & 0 deletions lessons/custom-express/src/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const getUsers = (req, res) => {
res.end('Fuck you beach')

return 'Get all users success'
}

module.exports = {
getUsers
}
Empty file.
11 changes: 11 additions & 0 deletions lessons/custom-express/src/user-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const Router = require('../framework/Router')
const userController = require('./user-controller')


const userEndpointsMap = {
'[/getUsers]:[GET]': userController.getUsers,
}

const userRouter = new Router(userEndpointsMap)

module.exports = userRouter
32 changes: 32 additions & 0 deletions lessons/modules/cluster.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const cluster = require('cluster')
const os = require('os')



/**
* If we are in main thread
*/
if (cluster.isMaster) {
console.log(`Parent thread pid: ${process.pid}`);

/**
* Create child threads
*/
for (let i = 0; /* i < os.cpus().length - 2 */ i < 3; i++) {
cluster.fork()
}
/**
* If thread has gone - create new thread (kill pid - command for killing process)
*/
cluster.on('exit', worker => {
console.log(`Worker with pid =${worker.process.pid} has gone`);
cluster.fork()
})
} else {
console.log(`Worker with pid =${process.pid} запущен`);

setInterval(() => {
console.log(`Worker with pid = ${process.pid} still is working`);

}, 5000)
}
23 changes: 23 additions & 0 deletions lessons/modules/event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const Emitter = require('events')

/**
* When is convenient to use?
* - http
* - websockets
* - long pulling
* - clusters
*/

const emitter = new Emitter()

/**
* on | once | removeListener(event, calllback) | removeAllListeners()
*/
emitter.on('message', (data, second, third) => {
console.log(`${data} | ${second} | ${third}`);
})


setTimeout(() => {
emitter.emit('message', 'some data', 'second arg', 'third arg')
}, 2000)
44 changes: 44 additions & 0 deletions lessons/modules/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const fs = require('fs')
/**
* В новых версиях ноды
*/
// const fsPromise = require('fs/promises')
const path = require('path')

function promisify(fn) {
return (...args) => {
return new Promise((res, rej) => {
fn(...args, (err, data) => {
if (err) {
rej(err)
return
}
res(data)
})
})
}

}

const promiseAppendFile = promisify(fs.appendFile)
const writeFilePromise = promisify(fs.writeFile)

writeFilePromise(path.join(__dirname, 'text.txt'), 'data')
.then(() => promiseAppendFile(path.join(__dirname, 'text.txt'),'\n123'))
.then(() => promiseAppendFile(path.join(__dirname, 'text.txt'),'\n456'))
.then(() => promiseAppendFile(path.join(__dirname, 'text.txt'),'\n789'))
.catch(e => console.log('Cautch some error!', e))



/* fs.mkdir(path.resolve(__dirname, 'dir', 'dir2'), {recursive: true}, (err)=> {
if (err) {
console.log(err)
return
}

console.log('Success!');

}) */


16 changes: 16 additions & 0 deletions lessons/modules/os.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const os = require('os')

console.log(os.platform);
console.log(os.arch());
console.log(os.cpus().length)

const cpus = os.cpus()

/**
* Можем распараллелить задачи
*/
for (let i = 0; i < cpus.length - 2; i++) {
const coreCPU = cpus[i]
console.log('Run one more node.js process', coreCPU);
}

15 changes: 15 additions & 0 deletions lessons/modules/path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const path = require('path')


__dirname //* global variable - abosulute path to current directory
/**
* Just join paths
*/
path.join(__dirname,'first', 'second'); // /home/lormida/../lessons/first/second

/**
* Joint paths, but always return abosulute path - works non-stable (depends on slashes)
*/
const fullPath = path.resolve('first', 'second') // /home/lormida/../lessons/first/second
path.parse(fullPath); // {root, dir, base, ext, name}

18 changes: 18 additions & 0 deletions lessons/modules/process.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const dotenv = require('dotenv')

dotenv.config()

// Variable from .env
console.log(process.env.PORT)
// Variable from cross-env running parameter
console.log(process.env.NODE_ENV)

// for example npm run proccess hello ->
/**
* [
* '/usr/bin/node',
* '/home/lormida/.../lessons/process.env',
* 'hello'
* ]
*/
console.log(process.argv);
16 changes: 16 additions & 0 deletions lessons/modules/stream.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* Stream !== Thread
*/

const fs = require('fs')
const path = require('path')
const http = require('http')

const server = http.createServer((req, res) => {
const readableStream = fs.createReadStream(path.join(__dirname, 'file.txt'))
// Readable stream не начинает читать новую порцию данных, пока writable не
// закончил читать предыдущую
readableStream.pipe(res)
})

server.listen(3000, ()=> console.log('success start listening...'))
4 changes: 4 additions & 0 deletions lessons/modules/text.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
data
123
456
789
18 changes: 18 additions & 0 deletions lessons/modules/url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const siteURL = 'http://localhost:8080/users?id=5123'

/**
* {
* href : 'http://localhost:8080/users?id=5123',
* origin : 'http://localhost:8080',
* protocol : 'http',
* host : 'localhost:8080',
* hostname : 'localhost',
* port : '8080',
* pathname : '/users',
* search : '?id=5123',
* searchParams: {id => '5123'}
* }

*/
const url = new URL(siteURL) //
console.log(url)
10 changes: 8 additions & 2 deletions server.js → lessons/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ const http = require('http')
const fs = require('fs')
const path = require('path')

/**
* Req is readable stream from client
* Res is writable stream on the server (which will be returned to the client)
* Res is stream, when we call res.end() - we close this stream and return it to the client
*/

const server = http.createServer((req, res) => {
if (req.method === 'POST') {
const body = []
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})

req.on('data', data => {
body.push(Buffer.from(data))
body.push(Buffer.from(data))
})

req.on('end', () => {
Expand Down
Loading