Node js Flashcards

1
Q

How does a multithreaded network app work?

A

Multithreaded network apps handle the above workload like this:

request ──> spawn thread
└──> wait for database request
└──> answer request
request ──> spawn thread
└──> wait for database request
└──> answer request
request ──> spawn thread
└──> wait for database request
└──> answer request
So the threads spend most of their time using 0% CPU waiting for the database to return data. While doing so they have had to allocate the memory required for a thread which includes a completely separate program stack for each thread etc. Also, they would have to start a thread which while is not as expensive as starting a full process is still not exactly cheap.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does Singlethreaded event loop work?

A

We don’t need to start a thread. So we do this:

request ──> make database request
request ──> make database request
request ──> make database request
database request complete ──> send response
database request complete ──> send response
database request complete ──> send response

The main advantage here is that we don’t need to spawn a new thread so we don’t need to do lots and lots of malloc which would slow us down.

It is like how a waiter works

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Where singlethreaded approach fails? Where multithreaded approach fails?

A

A single-threaded app fails big if you need to do lots of CPU calculations before returning the data. Now, I don’t mean a for loop processing the database result. That’s still mostly O(n). What I mean is things like doing Fourier transform (mp3 encoding for example), ray tracing (3D rendering) etc.

A multithreaded app fails big if you need to allocate lots of RAM per thread. First, the RAM usage itself means you can’t handle as many requests as a single threaded app.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

explain Hybrid approach (Single thread eventloop and thread pool)?

A

Some web servers use a hybrid approach. Nginx and Apache2 for example implement their network processing code as a thread pool of event loops. Each thread runs an event loop simultaneously processing requests single-threaded but requests are load-balanced among multiple threads.

Some single-threaded architectures also use a hybrid approach. Instead of launching multiple threads from a single process you can launch multiple applications - for example, 4 node.js servers on a quad-core machine. Then you use a load balancer to spread the workload amongst the processes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Name and explain the 4 types of errors in Node JS

A
  • Standard JavaScript errors such as Syntax error, Reference Error, Type Error, Evaluation Error, range error, URI Error and Internal Error.
  • System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist or attempting to send data over a closed socket.
  • User-specified errors triggered by application code.
  • AssertionErrors are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur. These are raised typically by the node:assert module.

======
Usually, in Node, you have 2 categories of errors: programmer errors (mistakes in the code) and operational errors (when an operation has the potential to fail).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are Streams?

A

Streams are objects that let you read data from a source or write data to a destination in a continuous fashion.

In Node.js, there are four types of streams:

  • Readable − Stream which is used for read operation.
  • Writable − Stream which is used for write operation.
  • Duplex − Stream which can be used for both read and write operations.
  • Transform − A type of duplex stream where the output is computed based on input.

Each type of Stream is an EventEmitter instance and throws several events at different instances of times. For example, some of the commonly used events are:

  • .data − This event is fired when there is data is available to read.
  • end − This event is fired when there is no more data to read.
  • .error − This event is fired when there is any error receiving or writing data.
  • .finish − This event is fired when all the data has been flushed to the underlying system.

https://www.tutorialspoint.com/nodejs/nodejs_streams.htm

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Buffer?

A

Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities, but the difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not be resizable.

To make an analogy, if you have a rollercoaster that can manage 30 people per time, the queue of the Rollercoaster would be the buffer. If 100 people arrive to the queue, only 30 will go to the rollercoaster and 70 will wait. If 1 person arrive to the queue, that person would have to wait to have at least 10 persons more to get into the rollercoaster.

The Buffer works like this. For instance, in a video, if your connection is slow, and you are watching a Youtube video, you would have to wait to have a minimal amount of data in the buffer to be able to see the video.

https://www.youtube.com/watch?v=br8VB99qPzE&ab_channel=Codevolution

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is the difference between setTimeout vs setInterval?

A

The setTimeout() method is used to call a function after a certain period of time. The setInterval() Javascript method is used to call a function repeatedly at a specified interval of time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Como generar paralelismo con NOde js?

A
  • Modulo ‘Cluster’
  • modulo ‘worker_threads: te permite crear subprocesos de trabajadores para ejecutar tareas en paralelo. Esto es útil para tareas intensivas en CPU.
  • con promises (pero no seria un paralelismo real sino mas bien del event loop)

En resumen, “cluster” es ideal para aplicaciones de servidor web que requieren escalabilidad y balanceo de carga, mientras que “worker_threads” es más apropiado cuando necesitas realizar tareas en paralelo a nivel de código JavaScript, especialmente en situaciones donde se realizan cálculos intensivos en CPU o se desean workers aislados.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Node js es interpretado o compilado?

A

Node.js es principalmente un entorno de ejecución de JavaScript basado en el motor V8 de Chrome. El código JavaScript en Node.js se interpreta en tiempo de ejecución, lo que significa que no se compila a código de máquina antes de ejecutarse, como sucede en lenguajes compilados como C++ o Java. En cambio, el código fuente de JavaScript se pasa directamente al motor V8, que lo interpreta y ejecuta línea por línea.

Esto ofrece ventajas en cuanto a flexibilidad y portabilidad, ya que el mismo código fuente JavaScript puede ejecutarse en diferentes plataformas sin necesidad de recompilarlo.

Es importante destacar que, aunque Node.js sea un entorno de ejecución interpretado, el ecosistema de Node.js incluye módulos y herramientas que pueden compilar ciertos componentes, como módulos nativos escritos en C++, para mejorar el rendimiento en tareas específicas. Sin embargo, el código JavaScript principal sigue siendo interpretado por el motor V8.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly