Node Flashcards
(27 cards)
What is Node.js? Where can you use it?
Node.js is a single-threaded, open-source, cross-platform runtime environment used to build server-side and networking applications. It uses event-driven, non-blocking I/O architecture, which makes it efficient and suitable for real-time applications.
Source: https://kinsta.com/knowledgebase/what-is-node-js/
Why use Node.js?
1) It uses fewer resources and memory (because it is single threaded),
2) it has wide adoption with many open source pacakages available,
3) it is multi-platform and
4) it simplifies the full stack as you can use just one language: Javascript.
Use: It’s best used for real time applications that aren’t data intensive. For programs that require more data processing a multi-threaded language like Java is a better choice.
Source: https://kinsta.com/knowledgebase/what-is-node-js/
What are the features of Node.js?
- Event-driven,non-blocking i/o model scalble network applications.
- built in module system for organizing code into reusable components.
- Support for multiple programming paradigms, including oop, functional and procedural.
- NPM, the largest ecosystem of open source libraries
- good support for real-time web applications
- Easy to learn for js dev
- cross platform support.
How do you update NPM to a new version in Node.js?
Explanation: With Mac or Linux systems it is rather easy just type the command npm install -g npm@latest into the terminal to update npm. With Windows it’s a little more complex as you will need to either modify the Window’s installation PATH or remove the npm files from the nodejs install directory then update npm in the terminal.
Source: https://docs.npmjs.com/try-the-latest-stable-version-of-npm
Why is Node.js Single-threaded?
Explanation: Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved instead of the typical thread-based implementation.
Source: https://www.simplilearn.com/tutorials/nodejs-tutorial/nodejs-interview-questions
Explain callback in Node.js.
Los callback son funciones que se pasan como argumento a otras funciones y se ejecutan después de que la función principal ha terminado de ejecutarse.
Los callback se utilizan para controlar el flujo de ejecución de una aplicación y para manejar la asincronia, que es una de las principales características de Nodejs.
Son útiles para tareas que pueden tardar un tiempo en completarse, como la lectura de archivos o la realización de solicitudes a un servidor, ya que permite a la aplicación continuar ejecutandose mientras se realiza la tarea asincrónica en segundo plano.
What is callback hell in Node.js?
Explanation: This is a big issue caused by coding with complex nested callbacks. Imagine each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected.
Use: This should be avoided.
Example:
fs.readdir(source, function (err, files) {
if (err) {
console.log(‘Error finding files: ‘ + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log(‘Error identifying file size: ‘ + err)
} else {
console.log(filename + ‘ : ‘ + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log(‘resizing ‘ + filename + ‘to ‘ + height + ‘x’ + height)
this.resize(width, height).write(dest + ‘w’ + width + ‘_’ + filename, function(err) {
if (err) console.log(‘Error writing file: ‘ + err)
})
}.bind(this))
}
})
})
}
}) //note this long line of stacking brackets is often a tell of callback hell
How do you prevent/fix callback hell?
Explanation: One of the most common ways is to use promises (an object that represents the eventual completion or failure of an async operation and its value). Once each step is finished and we have our value, we can run then() method to call the async callback or if it fails we can catch an error. We could also just keep our code shallow and modularize (make each block of code do one thing only).
Example:
houseOne()
.then(data=>console.log(data)
.then(houseTwo)
.then(data=>console.log(data)
.then(houseTwo)
Source: https://www.geeksforgeeks.org/what-is-callback-hell-in-node-js/
Explain the role of REPL in Node.js.
REPL (acronym for Read Eval Print Loop)
Es un interprete de comandos interactivo que permite a los desarrolladores probar y ejecutar código javascript de manera inmediata.
Su nombre describe el proceso de lectura de una linea, evaluación de la entrada, impresion de los resultados y vuelta al bucle para la siguiente linea de entrada.
Para usarlo solo escribimos node en la terminar y ya podemos ejecutar codigo js en la consola.
Name the types of API functions in Node.js.
Explanation: There are two types: Asynchronous, Non-blocking functions and Synchronous, Blocking functions
Example: Asynchronous examples would be emails and online forums. Synchronous examples would be instant messaging and video calls.
Source: https://www.geeksforgeeks.org/types-of-api-functions-in-node-js/
What are the functionalities of NPM in Node.js?
Explanation: NPM serves two main purposes:
1) being an online repository of open-source Node.js projects and
2) a command line utility for interacting with said repository.
Use: Typically it is used to install packages, manage versions and manage project dependencies.
Source: https://nodejs.org/en/knowledge/getting-started/npm/what-is-npm/
What is the difference between Node.js and Ajax?
Explanation: Node.js is an open-source server-side environment that makes it possible to run JavaScript outside of the browser. Ajax is a client-side web development technique used for making asynchronous calls to the server.
Use: You would use Node.js to create a server environment to interact with local files or dynamic files on the internet. Ajax is used to communicate with servers.
Source: https://www.geeksforgeeks.org/difference-between-nodejs-ajax-and-jquery/#:~:text=NodeJs%20is%20an%20open%2Dsource,javascript%20outside%20of%20the%20browser.
What are “streams” in Node.js? Explain the different types of streams present in Node.js.
Los streams son una característica fundamental de nodejs.
Representan una secuencia de datos que puede ser leidos o escritos de manera asincrónica.
En nodejs, los streams se pueden usar para manipular y procesar grandes cantidades de datos de manera eficiente.
Los tipos de streams que hay son :
1) de lectura: permiten leer datos de una fuente
2)de escritura: permiten escribir datos en un destino
3) de duplex: permiten tanto leer como escribirl datos. Son útiles para aplicaciones de comunicación en tiempo real.
4)transformation:duplex streams that can modify or transform the data as is written and read.
from the node website:
A stream is an abstract interface for working with streaming data in Node.js. The node:stream module provides an API for implementing the stream interface.
Explain chaining in Node.js.
Explanation: Promise chaining allows you to chain together multiple asynchronous tasks in a specific order.
Use: Chaining is great when you have complex code that has any number of asynchronous tasks that need to be performed after the completion of a different asynchronous task.
Example: The .then handler is used for promise chaining. After the initial promise resolves, the .then handler creates a new promise based on the result of the previous promise, and so on and so forth.
Source: https://javascript.info/promise-chaining
What are Globals in Node.js?
Explanation: Node.js Global Objects are the objects that are available in all modules. Global Objects are built-in objects that are part of the JavaScript and can be used directly in the application without importing any particular module.
They are common built-in modules, functions, strings and objects used widely in Node.
Funciones, objetos o variables que están disponibles en cualquier parte de la aplicación sin necesidad de ser importadas o requeridas.
Por ejemplo:
process (obj que proporciona info sobre el proceso actual de Node)
console (obj que permite imprimir info en la consola)
setTimeout and setInterval (funciones)
Buffer (obj que permite trabajar con datos binarios)
__dirname y __filename (variables que contienen el nombre del direction y archivo actual)
Example: setTimeout() is a global function used to run a callback after at least x milliseconds:
function printHello() {
console.log(‘Hello World!’);
}
//call printHello() after 2 seconds
setTimeout(printHello, 2000);
Source: https://www.tutorialspoint.com/nodejs/nodejs_global_objects.htm
What is Event-driven programming?
Event-driven programming refers to a programming paradigm where the flow of the program is determinated by events or changes in state, rather than following a predetermined sequence of instructions.
In the context of Node.js, the event-driven model means that the server can handle multiple requests simultaneously by registering events handlers for specific actions. When a request comes in, the event loop listens, and triggers the appropriate event handler, which performs the necessary actions.
Explanation: Event-driven programming is a programming paradigm where the control flow of the program is determined by occurance of events. The events are usually user interactions with the website such as clicking buttons, filling out forms, etc.
Use: The events are monitored by code known as event listeners.
Example: element.addEventListener(‘click’, function) will call a function upon clicking element
Source: https://www.computerhope.com/jargon/e/event-driven-prog.htm
What is Event loop in Node.js? And How does it work?
It is a loop that is responsable for monitoring the event queu and executing the appropriate event handlers for those events.
Each time an event occurs, it is placed in the event queue and waits to be processed by the event loop.
Explanation: The Event loop handles all async callbacks. We can attach listeners to events, and when a said event fires, the listener executes the callback we provided.
Use: Whenever we call setTimeout, http.get and fs.readFile, Node.js runs the operation and continues to run other code without waiting for the output. When the operation is finished, it receives the output and runs our callback function. All the callback functions are queued in an loop, and will run one-by-one when the response has been received.
Source: https://vigowebs.medium.com/frequently-asked-node-js-interview-questions-and-answers-b74fa1f20678
What is the purpose of module.exports in Node.js?
Explanation: In Node.js, a module encapsulates all related code into a single unit of code by moving all relevant functions into a single file.
Use: You may export a module with the module.exports function, which lets it be imported into another file using require
Source: https://www.simplilearn.com/tutorials/nodejs-tutorial/nodejs-interview-questions
What is the difference between Asynchronous and Non-blocking?
Async refers to the ability of a function or process to run independently of the main program flow and returns control to main flow once it has finished. This allows other functions or tasks to be executed while the async function is running.
Non-blocking on the other hand, refers to the ability of a function or process to return immediately without waiting for the competition of a long-running operation. Instead, it returns a placeholder got the result, which can be acted upon later once the operation has completed.
all async are non-blocking but not all non-blocking are async.
What is Tracing in Node.js?
Tracing en Nodejs se refiere al proceso de rastrear y registrar los detalles de la ejecucion de una aplicación. Esto incluye información sobre el tiempo de ejecución de las funciones, el uso de la cpu y memoria y otros datos relevantes para entender como funciona una aplicación y resolver problemas.
El tracing se puede hacer :
- con la api de tracing de nodejs
- con herramientas de monitoreo de aplicaciones como dev tools,
- logging
Explanation: Tracing provides a mechanism to collect tracing information generated by V8, Node core and userspace code in a log file.
Use: Tracing can be enabled by passing the –trace-events-enabled flag when starting a Node.js application. The set of categories for which traces are recorded can be specified using the –trace-event-categories flag followed by a list of comma separated category names. By default the node and v8 categories are enabled. Log files can be opened in the chrome://tracing tab of Chrome.
Source: https://vigowebs.medium.com/frequently-asked-node-js-interview-questions-and-answers-b74fa1f20678
How will you debug an application in Node.js?
Explanation: Typically using the debugger utility and console.log(). I would place debugger statements in the code wherever I would like a breakpoint inserted and then run the script with node and debug enabled.
Source: https://vigowebs.medium.com/frequently-asked-node-js-interview-questions-and-answers-b74fa1f20678
Difference between setImmediate() and setTimeout()?
Explanation: setImmediate() is to schedule the immediate execution of callback after I/O (input/output) event callbacks and before setTimeout and setInterval. setTimeout() is to schedule execution of a one-time callback after delay milliseconds. both are async.
Use: Inside an I/O cycle, the setImmediate() should execute before setTimeout({},0).
Example:
const fs = require(‘fs’);
fs.readFile(__filename, () => {
setTimeout(() => {
console.log(‘timeout’);
}, 0);
setImmediate(() => {
console.log(‘immediate’);
});
});
Source: https://dev.to/ynmanware/setimmediate-settimeout-and-process-nexttick-3mfd
What is process.nextTick()?
Explanation: Every time the event loop takes a full trip, we call it a tick. When we pass a function to process.nextTick(), we instruct the engine to invoke this function at the end of the current operation, before the next event loop tick starts. process.nextTick() is actually faster
Use: Calling setTimeout(() => {}, 0) will execute the function at the end of next tick, much later than when using nextTick() which prioritizes the call and executes it just before the beginning of the next tick.
Example:
process.nextTick(() => {
// do something
});
Source: https://nodejs.dev/learn/understanding-process-nexttick
What is package.json? What is it used for?
Explanation: All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. It’s a central repository of configuration for tools, for example. It’s also where npm and yarn store the names and versions for all the installed packages.
Use: This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.
Source: https://nodejs.org/en/knowledge/getting-started/npm/what-is-the-file-package-json/