1. What is Node.js?
Node.js is an open-source server side runtime environment built on Chrome’s V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.
2. What are the benefits of using Node.js?
From a web server development perspective Node has a number of benefits:
Great performance! Node was designed to optimize throughput and scalability in web applications and is a good solution for many common web-development problems (e.g. real-time web applications).
Code is written in “plain old JavaScript”, which means that less time is spent dealing with “context shift” between languages when you’re writing both client-side and server-side code.
JavaScript is a relatively new programming languages and benefits from improvements in language design when compared to other traditional web-server languages (e.g. Python, PHP, etc.) Many other new and pouplar languages compile/convert into JavaScript so you can use TypeScript, CoffeeScript, ClojureScript, Scala, LiveScript, etc.
The node package manager (NPM) provides access to hundres of thousands of resuable packages. It also has best-in-class dependency resolution and can also be used to automate most of the build toolchain.
Node.js is portable. It is available on Microsoft Windows, macOS, Linux, Solaris, FreeBSD, OpenBSD, WebOS, and NonStop OS. Furthermore, it is well-supported by many web hosting providers, that often provide specific infrastrucutre and documentation for hosting Node sites.
It has a very active third party ecosystem and developer community, with lots of people who are willing to help.
3. What are the data types in Node.js?
Primitive Types:
String
Number
Boolean
Undefined
Null
RegExp
Buffer: Node.js includes an additional data type called Buffer (not available in browser’s JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.
4. What does the runtime environment mean in Node.js?
The Node.js runtime is the software stack responsible for installing your web service’s code and its dependencies and running your service.
The Node.js runtime for App Engine in the standard environment is declared in the app.yaml file:
runtime: nodejs10
The runtime environment is literally just the environment your application is running in. This can be used to describe both the hardware and the software that is running your application. How much RAM, what version of node, what operating system, how much CPU cores, can all be referenced when talking about a runtime environment.
5. Explain usage of NODE_ENV?
NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value.
For example, when we work on a project and there are production and development environments. We don’t need to use caching in the development env. So we set
$ NODE_ENV=development
and use the code below
if (process.env.NODE_ENV === 'development')
useCaching = false;
/* Upon that, if the project runs on production it will use caching. */
6. What are the core modules of Node.js?
They are defined within the Node.js source and are located in the lib/ folder, and Node.js has several modules compiled into the binary.
Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require(‘http’) will always return the built in HTTP module, even if there is a file by that name.
Core modules can also be identified using the node: prefix, in which case it bypasses the require cache. For instance, require(‘node:http’) will always return the built in HTTP module, even if there is require.cache entry by that name.
7. What is asynchronous programming in Node.js?
Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed). There are numerous benefits to using it, such as improved application performance and enhanced responsiveness.
8. What is the difference between Asynchronous and Non-blocking?
a. Asynchronous
The architecture of asynchronous explains that the message sent will not give the reply on immediate basis just like we send the mail but do not get the reply on an immediate basis. It does not have any dependency or order. Hence improving the system efficiency and performance. The server stores the information and when the action is done it will be notified.
b. Non-Blocking
Nonblocking immediately responses with whatever data available. Moreover, it does not block any execution and keeps on running as per the requests. If an answer could not be retrieved than in those cases API returns immediately with an error. Nonblocking is mostly used with I/O(input/output). Node.js is itself based on nonblocking I/O model. There are few ways of communication that a nonblocking I/O has completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a callback function.
Asynchronous VS Non-Blocking
Asynchronous does not respond immediately, While Nonblocking responds immediately if the data is available and if not that simply returns an error.
Asynchronous improves the efficiency by doing the task fast as the response might come later, meanwhile, can do complete other tasks. Nonblocking does not block any execution and if the data is available it retrieves the information quickly.
Asynchronous is the opposite of synchronous while nonblocking I/O is the opposite of blocking. They both are fairly similar but they are also different as asynchronous is used with a broader range of operations while nonblocking is mostly used with I/O.
9. Name the types of API functions in Node.js?
There are two types of API functions in Node.js:
Asynchronous, Non-blocking functions
Synchronous, Blocking functions
// a. 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.
// 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
*/
// b. 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.
// 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.
*/
10. How does Node.js handle child threads?
Node.js is a single threaded language which in background uses multiple threads to execute asynchronous code. Node.js is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads. That is handled by Node.js run-time.
Nodejs Primary application runs in an event loop, which is in a single thread.
Background I/O is running in a thread pool that is only accessible to C/C++ or other compiled/native modules and mostly transparent to the JS.
Node v11/12 now has experimental worker_threads, which is another option.
Node.js does support forking multiple processes ( which are executed on different cores ).
It is important to know that state is not shared between master and forked process.
We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.
11. What is the preferred method of resolving unhandled exceptions in Node.js?
Unhandled exceptions in Node.js can be caught at the Process level by attaching a handler for uncaughtException event.
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
Process is a global object that provides information about the current Node.js process. Process is a listener function that is always listening to events.
Few events are :
Exit
disconnect
unhandledException
rejectionHandled
12. How Node.js read the content of a file?
The “normal” way in Node.js is probably to read in the content of a file in a non-blocking, asynchronous way. That is, to tell Node to read in the file, and then to get a callback when the file-reading has been finished. That would allow us to hand several requests in parallel.
Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
Read Files
<!-- index.html -->
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
// read_file.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
/*
Initiate read_file.js:
node read_file.js
*/