NodeJS Flashcards
what is nodejs?
it’s a javascript runtime
what is a main difference between nodejs and php?
nodejs actually writes the server like listening but php just writes the code that executes on the server
what is the function u use to import files into a file?
require
what is a core module we use to make a server?
http
what is an architecture that node heavily depends on?
event driven structure
how many threads does node use?
it’s one threaded process
what is an event loop?
it keeps running as long as event listeners are registered
what is the general concept of node?
when x happens do y
how to create a server?
require http then http.createServer()
then listen on the server server.listen();
how to redirect to another page?
using response.setHeader(‘location’ , ‘’);
how should u end your response when creating a server?
response.end()
what is the request body?
it’s a stream
what is a stream?
it’s a continuous collection of data that is sent in chunks so that we can parse each chunk without waiting for it all to come
how to work with streams of data?
with buffers
what is a buffer?
it’s a construct that allows u to work with a chunk of data before it’s actually fully parsed
how to use a buffer to read the request body?
by registering a listener with the method ‘on’ and the listen for ‘data’ and u take every chunk and then register another listener called ‘end’ and user a ‘Buffer’ to concat all ur chunks
what is the difference between writeFile and writeFileSync?
writeFileSync blocks the code but writeFile is asynchronus which is non blocking
what does event loop handles?
handle event callbacks only that are fast operations
what handles the heavy and slow code of nodejs like handling large file systems?
the worker pool
what is the worker pool?
it does all the heavy lifting and it’s detached from the event loop and nodejs and it has different threads and once it’s done it will trigger the callback in the event loop
what is the event loop?
a loop which is started by nodejs and keeps the process running and handles all the callbacks
what is the order of the event loop?
in the beginning of each loop it checks if
1 - there is any timer that it should execute
2 - pending callbacks :executes code that is deferred by the poll phase
a - if it should call it
b - or it’s already finished from the worker pool
3 - a poll phase which registers new call backs or it checks if it can finish it or defer it to a pending callback
4 - check phase which executes setImmediate() callbacks
5 - close callbacks which executes all ‘close’ event callbacks
when can we exit the event loop?
if there is no registered event callbacks