{"componentChunkName":"component---src-components-blogpost-blogpost-jsx","path":"/blog/NodeJS2/","result":{"data":{"site":{"siteMetadata":{"title":"K011"}},"mdx":{"id":"859f6462-382a-5921-a37b-b8f3e68c017a","body":"var _excluded = [\"components\"];\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsxRuntime classic */\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Node Works\",\n  \"date\": \"2021-05-26\",\n  \"description\": \"Event loop, threads ...\"\n};\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, _excluded);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Node Architecture\"), mdx(\"p\", null, \"Node depends on a set of libraries which is what makes it node. Some of these are:\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"http-parser\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"c-ares\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"OpenSSL\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"zlib\")), mdx(\"p\", null, \"but the 2 main libraries are:\"), mdx(\"h3\", null, \"V8(c++ and js)\"), mdx(\"p\", null, \"this is the js interpreter and compiler in chrome but it is also node's by definition the one that is in charge of converting the code made in js into a low level code (from js to bytecode and then to machine code).\"), mdx(\"h3\", null, \"libuv\"), mdx(\"p\", null, mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"Unicorn velociraptor library\"), \".\\nthis library provides many of the things that make node work.some of these functions are access to the computer\\u2019s file system, operating system, networking, and more.the most important functionality's are the event loop and thread pool\"), mdx(\"h2\", null, \"Process\"), mdx(\"center\", null, mdx(\"img\", {\n    src: \"https://imgur.com/Huo8FNl.jpg\"\n  })), \"Node.js application run on a single thread.think of the thread as a program(instructions).Since the node is single-threaded, you have to be careful not to block it. So be careful with:\", mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"using sync versions of fs, crypto or zlib module functions within callback functions.\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"performing complex calculations (>O(n^2)).\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"using complex regular expressions (e.g. nested quantifiers).\")), mdx(\"p\", null, \"when a node.js app initializes, modules are imported, the top-level code is executed, and then callbacks are registered. Then, the event loop start.\\nThe event loop performs all the operations of the application but some of them are too heavy. as for example:\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"file system APIs\")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"encryption\")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"DNS lookups\")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"compresion\"))), mdx(\"p\", null, \"In these cases node takes care and offloads the task to a thread pool, \"), mdx(\"h3\", null, \"Event loop\"), mdx(\"center\", null, mdx(\"img\", {\n    src: \"https://imgur.com/LPOEXR4.jpg\"\n  })), mdx(\"p\", null, \"Any code inside the callback functions is executed inside the event loop. That is to say, this is where all the asynchronous code is executed.\\nWhen we start our application, the event loop begins executing immediately. Each phase of the event loop has its own callback queue. Some of these phases are more important than others, the most important being\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"callbacks of expired timers (e.g., setTimeout()).\")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"handle I/O polling, i.e., it looks for I/O processes that need to be executed and puts them in the callback queue of the phase. Since I/O encompasses network and file access, about 99% of the code we write is handled by this phase. \")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"setImmediate() callbacks, which are special timers that are executed after the I/O polling phase. The final phase (for our purposes) handles shutdown callbacks, for example, when a web server shuts down.\")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"p\", {\n    parentName: \"li\"\n  }, \"the process.nextTick() queue and the other microtask queue (which includes promises). These two queues have their own pattern.\"))), mdx(\"p\", null, \"If they have anything in their callback queues, they will be executed after the completion of any of the four phases described above.\\nWhen the event loop has gone through all four phases, it needs to check whether to run the loop again or just exit the program. It does this by checking to see if there are any I/O processes or timers running in the background. If there are, the event loop goes back to the beginning and repeats itself.\\nthe events are emitted.\\nthe idea of the event loop is that:\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"Events are emitted, events are emitted from an asynchronous function such as receiving an HTTP request, the fileSystem module or a timer has finished.\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"Afterwards, the event loop picks them up. The callback functions are executed and as mentioned above, event-loop offloads the heaviest tasks to the thread-pool.\")), mdx(\"a\", {\n    href: \"https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick\"\n  }, \".\"), mdx(\"h2\", null, \"The event-driven architecture\"), mdx(\"hr\", null), mdx(\"p\", null, \"Node has objects called event emitters. They emit events when a file is read, when a timer ends, or when a network request is made, among other things. These events are picked up by the event listener that we can configure.an example of this is when we want to create a server.\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \" const server = http.createServer();\\n server.on('request', (req, res) => {\\n  console.log('request receved');\\n  res.end('request receved');\\n });\\n\")), mdx(\"p\", null, \"This 'server.on' is actually how we create a listener and it listens for a request.\\nSo let's say we have our server running and a new request is made.\\nThe server acts as a sender and will automatically emit an event called \\\"request\\\" every time a request comes to the server, then the callback function attached to this listener will be called and send some data back to the clients.This is an example of the Observer , where a listener is constantly waiting for an event from a sender. \"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"const EventEmitter = require('events');\\nconst myEmitter = new  EventEmitter();\\nmyEmitter.on('myevent',()=>{       //Observer 1\\n        console.log('Oh k0')   \\n});\\nmyEmitter.on('myevent',name=>{       //Observer 1 \\n        console.log(`Oh ${name}`)       \\n});\\nmyEmitter.emit('myevent', \\\"Pablo\\\") // object that emits the event\\n\")), mdx(\"h3\", null, \"Streams\"), mdx(\"hr\", null), mdx(\"p\", null, \"A Stream is a collection of data that is not available all at once, since it is transmitted piece by piece (called chunks). This allows you to read and write each chunk without waiting for all the data to be available.\\nStreams work by default with buffers, as long as it has not been specifically configured to work with objects.\", mdx(\"strong\", {\n    parentName: \"p\"\n  }, \"Streams are instances of an EventEmitter class\"), \" So they can receive and send events.\"), mdx(\"p\", null, \"This is used to avoid the error when the node memory is exceeded, since node has a memory limit of 2gb. This happens because with the streams we are working piece by piece and this is freeing memory as the information is used.\\nThink of youtube or netflix, they are called stream platforms because they use the same principle (they load each video chunk by chunk).\"), mdx(\"p\", null, \"In node there are 4 fundamental types:\"), mdx(\"h3\", null, \"Redable streams\"), mdx(\"p\", null, \"These streams are the ones that can read information (consume data). An example of these streams can be when there is an http request (the data that comes from a server is received piece by piece) another example can be with file system because when we read a file we read it piece by piece (fs read).\"), mdx(\"h4\", null, \"The most important events\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"data:\"), \"The data event is emitted when there is a new piece of data to consume.\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"end:\"), \"The end event a is emitted when there is no more piece of data to consume.\")), mdx(\"h4\", null, \"The most important functions\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"pipe():\"), \" the method used to take a readable stream and connect it to a writeable stream. \")), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"readableSource.pipe(writeableDest)\\n\")), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"read():\"))), mdx(\"h4\", null, \"Example\"), mdx(\"p\", null, \"for example to upload a file to the page\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"  server.on('request', (req, res) => {\\n   fs.readFile('text-file.txt', (err, data) => {\\n     res.end(data)\\n   });\\n  });\\n\")), mdx(\"p\", null, \"This will load the entire file into memory when there is a request, so if the file is very large it will take a long time to load:\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"  server.on(\\\"request\\\", (req, res) => {\\n  const readable = fs.createReadStream(\\\"text-file.txt\\\");\\n  readable.on(\\\"data\\\", chunk => {\\n    res.write(chunk);\\n  });\\n  readable.on(\\\"end\\\", () => {\\n    res.end();\\n  });\\n});\\n\")), mdx(\"p\", null, \"or we can also used pipe\"), mdx(\"pre\", null, mdx(\"code\", {\n    parentName: \"pre\",\n    \"className\": \"language-js\"\n  }, \"  server.on(\\\"request\\\", (req, res) => {\\n  const readable = fs.createReadStream(\\\"text-file.txt\\\");\\n  readable.pipe(res)\\n});\\n\")), mdx(\"h3\", null, \"Writable streams\"), mdx(\"p\", null, \"These streams unlike the redable streams are the ones that can write and manipulate data. Some examples of these streams are when there is an http response (when we send back to the client) this is a writable stream another example would be with file system when we write a file (fs write) piece by piece. \"), mdx(\"h4\", null, \"The most important events\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"drain:\"), \"The data event is emitted when there is a new piece of data to consume.\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"end:\", mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"end:\"), \"The end event a is emitted when there is no more piece of data to consume.\")), mdx(\"h4\", null, \"The most important functions\"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"write()\")), mdx(\"li\", {\n    parentName: \"ul\"\n  }, mdx(\"strong\", {\n    parentName: \"li\"\n  }, \"end()\"), \" \")), mdx(\"h3\", null, \"Duplex streams\"), mdx(\"p\", null, \"We can say that these streams are a combination of the 2 previous ones since they can read and write at the same time. They are less common than the previous ones but it does not make them less important. An example of this would be a web socket of a module.\"), mdx(\"h3\", null, \"Transform streams\"), mdx(\"p\", null, \"This stream is a duplex stream, but it can edit, transform the data being read. A good example of this stream is the core module zlib or gzip.\"));\n}\n;\nMDXContent.isMDXComponent = true;","frontmatter":{"title":"Node Works","date":"2021-05-26","description":"Event loop, threads ..."}},"allMdx":{"edges":[{"node":{"frontmatter":{"title":"Classification","date":"2021-11-03","description":"Naive Bayes, Discriminant Analysis, Logistic Regression"},"fields":{"slug":"/blog/est4/"}}},{"node":{"frontmatter":{"title":"Regression and Prediction","date":"2021-11-02","description":"REGRESSION"},"fields":{"slug":"/blog/est3/"}}},{"node":{"frontmatter":{"title":"Distribution","date":"2021-11-01","description":"Data distributions"},"fields":{"slug":"/blog/est1/"}}},{"node":{"frontmatter":{"title":"Stats Testing","date":"2021-11-01","description":"Statistical Experiments and significance testing"},"fields":{"slug":"/blog/est2/"}}},{"node":{"frontmatter":{"title":"Recursion","date":"2021-08-26","description":"Algorithm recursion"},"fields":{"slug":"/blog/alg1/"}}}]}},"pageContext":{"slug":"/blog/NodeJS2/","id":"859f6462-382a-5921-a37b-b8f3e68c017a"}},"staticQueryHashes":["63159454"]}