Node Flashcards

1
Q

What is Node.js? Where can you use it?

A

“Node.js is a run-time JavaScript environment built on top of Chrome’s V8 engine. It uses an event-driven, non-blocking I/O model. It is lightweight and so efficient. Node.js has a package ecosystem called npm.
Node.js can be used to build different types of applications such as web application, real-time chat application, REST API server etc. However, it is mainly used to build network programs like web servers, similar to PHP, Java, or ASP.NET. Node.js was developed by Ryan Dahl in 2009.

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

Why use Node.js?

A

Node is fast, efficient and scalable, event driving, no i/o blocking, asynchronous, you can use the same language on the front and back end.

“Node.js makes building scalable network programs easy. Some of its advantages include:
It is generally fast
It almost never blocks
It offers a unified programming language and data type
Everything is asynchronous
It yields great concurrency

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

What are the features of Node.js?

A

“It is asynchronous and event driven
Super fast- being built on google chrome’s v8 engine
Single threaded but highly scalable

Node.js is a single-threaded but highly scalable system that utilizes JavaScript as its scripting language. It uses asynchronous, event-driven I/O instead of separate processes or threads. It is able to achieve high output via single-threaded event loop and non-blocking I/O.

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

How do you update NPM to a new version in Node.js?

A

“You use the following commands to update NPM to a new version:

$ sudo npm install npm -g
/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
npm@2.7.1 /usr/lib/node_modules/npm”

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

Why is Node.js Single-threaded?

A

Node.js is single-threaded for asynchronous processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based loads.

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

Explain callback in Node.js.

A

A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking. Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.

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

What is callback hell in Node.js?

A

“Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain. For example:

query(""SELECT clientId FROM clients WHERE clientName='picanteverde';"", function(id){
  query(""SELECT * FROM transactions WHERE clientId="" + id, function(transactions){
    transactions.each(function(transac){
      query(""UPDATE transactions SET value = "" + (transac.value*0.1) + "" WHERE id="" + transac.id, function(error){
        if(!error){
          console.log(""success!!"");
        }else{
          console.log(""error"");
        }
      });
    });
  });
});"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you prevent/fix callback hell?

A

“The three ways to prevent/fix callback hell are:

Handle every single error
Keep your code shallow
Modularize – split the callbacks into smaller, independent functions that can be called with some parameters then joining them to achieve desired results.
The first level of improving the code above might be:

var logError = function(error){
    if(!error){
      console.log(""success!!"");
    }else{
      console.log(""error"");
    }
  },
  updateTransaction = function(t){
    query(""UPDATE transactions SET value = "" + (t.value*0.1) + "" WHERE id="" + t.id, logError);
  },
  handleTransactions = function(transactions){
    transactions.each(updateTransaction);
  },
  handleClient = function(id){
    query(""SELECT * FROM transactions WHERE clientId="" + id, handleTransactions);
  };

query(““SELECT clientId FROM clients WHERE clientName=’picanteverde’;”“,handleClient);

You can also use Promises, Generators and Async functions to fix callback hell.”

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

Explain the role of REPL in Node.js.

A

“As the name suggests, REPL (Read Eval print Loop) performs the tasks of – Read, Evaluate, Print and Loop. The REPL in Node.js is used to execute ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical.

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

Name the types of API functions in Node.js.

A

“There are two types of functions in Node.js.:

Blocking functions - In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously
For example:
const fs = require(‘fs’);
const data = fs.readFileSync(‘/file.md’); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log

The second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after Console.log

Non-blocking functions - In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions execute asynchronously.
For example:

const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
  if (err) throw err;
  console.log(data);
});
// moreWork(); will run before console.log

Since fs.readFile () is non-blocking, moreWork () does not have to wait for the file read to complete before being called. This allows for higher throughput. “

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

What are the functionalities of NPM in Node.js?

A

“NPM (Node package Manager) provides two functionalities:

Online repository for Node.js packages
Command line utility for installing packages, version management and dependency management of Node.js packages”

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

What is the difference between Node.js and Ajax?

A

“Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementation of JavaScript. They all serve completely different purposes.

Ajax is primarily designed for dynamically updating a particular section of a page’s content, without having to update the entire page.

Node.js is used for developing client-server applications.”

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

What are “streams” in Node.js? Explain the different types of streams present in Node.js.

A

“Streams are objects that allow reading of data from the source and writing of data to the destination as a continuous process.

There are four types of streams.

to facilitate the reading operation
to facilitate the writing operation
to facilitate both read and write operations
is a form of Duplex stream that performs computations based on the available input “

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

Explain chaining in Node.js.

A

Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.

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

What are Globals in Node.js?

A

“Three keywords in Node.js constitute as Globals. These are:

Global – it represents the Global namespace object and acts as a container for all other  objects.
Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment. 
Buffer – it is a class in Node.js to handle binary data. "
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Event-driven programming?

A

“Event-driven programming is building our application based on and respond to events. When an event occurs, like click or keypress, we are running a callback function which is registered to the element for that event.
Event driven programming follows mainly a publish-subscribe pattern.”

17
Q

What is Event loop in Node.js work? And How does it work?

A

“The Event loop handles all async callbacks. Node.js (or JavaScript) is a single-threaded, event-driven language. This means that we can attach listeners to events, and when a said event fires, the listener executes the callback we provided.
Whenever we are call setTimeout, http.get and fs.readFile, Node.js runs this operations and further continue to run other code without waiting for the output. When the operation is finished, it receives the output and runs our callback function.
So all the callback functions are queued in an loop, and will run one-by-one when the response has been received.”

18
Q

What is Event loop in Node.js work? And How does it work?

A

“The Event loop handles all async callbacks. Node.js (or JavaScript) is a single-threaded, event-driven language. This means that we can attach listeners to events, and when a said event fires, the listener executes the callback we provided.
Whenever we are call setTimeout, http.get and fs.readFile, Node.js runs this operations and further continue to run other code without waiting for the output. When the operation is finished, it receives the output and runs our callback function.
So all the callback functions are queued in an loop, and will run one-by-one when the response has been received.”

19
Q

What is the purpose of module.exports in Node.js?

A
"A module encapsulates related code into a single unit of code. This can be interpreted as moving all related functions into a file. Imagine that we created a file called greetings.js and it contains the following two functions:
"
20
Q

What is the difference between Asynchronous and Non-blocking?

A

“Asynchronous literally means not synchronous. We are making HTTP requests which are asynchronous, means we are not waiting for the server response. We continue with other block and respond to the server response when we received.

The term Non-Blocking is widely used with IO. For example non-blocking read/write calls return with whatever they can do and expect caller to execute the call again. Read will wait until it has some data and put calling thread to sleep.”

21
Q

What is Tracing in Node.js?

A

Tracing provides a mechanism to collect tracing information generated by V8, Node core and userspace code in a log file. Tracing can be enabled by passing the –trace-events-enabled flag when starting a Node.js application.

22
Q

How will you debug an application in Node.js?

A

“Node.js includes a debugging utility called debugger. To enable it start the Node.js with the debug argument followed by the path to the script to debug.
Inserting the statement debugger; into the source code of a script will enable a breakpoint at that position in the code:”

23
Q

Difference between setImmediate() vs setTimeout()?

A

“setImmediate() and setTimeout() are similar, but behave in different ways depending on when they are called.
setImmediate() is designed to execute a script once the current poll (event loop) phase completes.
setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.
The order in which the timers are executed will vary depending on the context in which they are called. If both are called from within the main module, then timing will be bound by the performance of the process.”

24
Q

What is process.nextTick()?

A

“process.nextTick() processes all callback functions and resolves it before the event loop continues.

setImmediate() and setTimeout() are based on the event loop. But process.nextTick() technically not part of the event loop. Instead, the nextTickQueue will be processed after the current operation completes, regardless of the current phase of the event loop.
Thus, any time you call process.nextTick() in a given phase, all callbacks passed to process.nextTick() will be resolved before the event loop continues.”

25
Q

What is package.json? What is it used for?

A

“This file holds various metadata information about the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies.
Some of the fields are: name, name, description, author and dependencies.
When someone installs our project through npm, all the dependencies listed will be installed as well. Additionally, if someone runs npm install in the root directory of our project, it will install all the dependencies to ./node_modules directory.”

26
Q

What is libuv?

A

“Libuv is the library that provides the event loop to Node.js.

Some of the features of libuv are:
Full-featured event loop backed by epoll, kqueue, IOCP, event ports.
Asynchronous TCP and UDP sockets
Asynchronous file and file system operations
Child processes
File system events

libuv is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it’s also used by Luvit, Julia, pyuv, and others.
When the node.js project began in 2009 as a JavaScript environment decoupled from the browser, it is using Google’s V8 and Marc Lehmann’s libev, node.js combined a model of I/O – evented – with a language that was well suited to the style of programming; due to the way it had been shaped by browsers. As node.js grew in popularity, it was important to make it work on Windows, but libev ran only on Unix. libuv was an abstraction around libev or IOCP depending on the platform, providing users an API based on libev. In the node-v0.9.0 version of libuv libev was removed.

27
Q

What are some of the most popular modules of Node.js?

A
"There are many most popular, most starred or most downloaded modules in Node.js. Some of them are:
express
async
browserify
socket.io
bower
gulp
grunt"
28
Q

What is EventEmitter in Node.js?

A

“All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.
When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously.”