node Flashcards
what is node js
javscript runtime environment that runs javascript outside of browser. its built in google chromes v8 engine
is it single thread?
yes. io operations can be run separate from the main application flow. it runs on a single thread. so multiple requests can be managed effectively.without managing threads
event loop
when node js starts, it initializes the event loop. io operations or http requests are processed as and when they occurs. they run separately from main thread so concurrency acheived.
phases of event loop
timers, check, idle, prepare, io callbacks, poll, close callbacks etc
event queue
stores incoming events in order, and pass them one by one to event loop
api pool
it has all apis by node js to execute blocking events async. if something is a blocking event, then it is given to api pool and once it is processed what it was waiting for, then it enters the event queue
let and var
Summary
Scope: var is function-scoped, while let is block-scoped.
Hoisting: Both var and let are hoisted, but let has a temporal dead zone.
Redeclaration: var allows redeclaration within the same scope; let does not.
In general, it is recommended to use let for variable declarations to avoid issues related to hoisting and redeclaration, and to benefit from block scope.
event emitters and listeners
myemitter = new EventEmitter()
myemitter.on => listener - emit multiple times
myemitter.once => listener - emit only once
myemitter.emit => calling emitter
// Listen for the ‘eventName’ event
myEmitter.on(‘eventName’, (data) => {
console.log(Event received with data: ${data}
);
});
// Emit an event named ‘eventName’ with data
myEmitter.emit(‘eventName’, ‘some data’);
exports
for creating modules. each file is treated as module.
// math.js
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;
// Usage in another file
const math = require(‘./math’);
console.log(math.add(2, 3)); // Output: 5
console.log(math.subtract(5, 2)); // Output: 3