1) What is Node.js?
Node.js is a JavaScript run-time built on Chrome's V8 JavaScript engine.
Nodejs is an open-source, cross-platform and JavaScript run-time environment. It is a lightweight framework used to develop server-side web applications.
Node.js is built upon Google Chrome’s V8 run-time—written in C++, built for multiple operating systems and super fast.
The use of JavaScript also means that transforming JSON data—the most common data interchange format on the Web—is fast by default.
Node.js used for creating large scale application development, mostly used for video streaming websites, single page application, and other web applications.
Setup a Node.js Development Environment on Windows, Mac and Linux -
It is easy to install Node.js on Mac, Windows and Linux. Simply you can go to Node.js official site and download you installer (Mac, Windows and Linux), and then execute the installer as per you and after that your window installer you received a text messages looks like, “Congrats!! You successfully installed Node.js on Windows!!”
Node.js Installer Following Steps,
1. Download the Windows installer from Nodejs.org official site.
2. Click and Run the installer (.msi installer package).
3. Follow the prompts instructions of the installer (Accept the agreement and click the NEXT button)
4. Restart your computer to get everything working in your command line interface (CLI).
Download Installer,
Download Node.js built installer and source code as for you, for Window, Mac and Linux with NPM and after that you can start developing applications.
The NPM is located in the directory where the Node.js is installed.
Update to Node.js, simply goes to Node.js official site and downloads Windows, Mac and Linux installer, and then executes the installer. Now your latest version of Node.js is updated on your machine.
2) Why Node.js?
The main reasons to use Node for what I do - which is building backend APIs for mobile and web application:
1. Non-blocking asynchronous I/O (blocking I/O doesn’t scale for high concurrency)
2. Single-threaded event loop (like nginx and Redis - read: FAST)
3. Event-driven servers
4. Real lexical closures (like Haskell and Scheme - unlike Java and C++)
5. Built-in support for promises and generator-based Coroutines
6. HTTP/2 in the core (I don’t know of any other language/runtime that has a built-in support for HTTP/2 with no need to install any dependencies, at the time of this writing)
7. Excellent support for building REST, GraphQL and WebSocket servers, with Socket.io for legacy clients.
3) Who Is the creator of Node.js?
Ryan Dahl is the creator of Node.js. The development was sponsored by Joyent.
4) When it was initially released?
It was initially released in 2009.
5) In which Language Node Js is written?
Node.js is written in C, C++, and JavaScript. It uses Google’s open source V8 JavaScript Engine to convert JavaScript code to C++.
6) What Is npm?
The NPM is Node.js' package ecosystem. It is the largest ecosystem of open-source libraries in the world. It is also the name of the command line package manager used to interact with npm.
Uninstall Node.js and NPM -
You can uninstall Node.js and NPM same as like your other software. The following steps as below,
1. Open your windows control panel.
2. Choose the programs & features option.
3. Click to “uninstall a program”.
4. Select installed Node.js, and click the uninstall link.
5) What is the name of the file which npm uses to identify the project and its dependencies?
Its name is package.json.
8) Can we use other Engines than V8?
Yes! Microsoft Chakra is another JavaScript engine which can be used with Node.js. It’s not officially declared yet.
9) What Are Benefits of using Node.js?
1. Very Fast
2. Asynchronous
3. Scalable
4. Open Source
5. No Buffering
6. Highly optimized V8 engine
7. Excellent JIT
8. Fantastic library of ready to use modules on npm
9. Great support for C++ extensions if you need threads for CPU-bound operations
10. A lots of great test frameworks, linters and other tooling
10) What Is the current version of Nodejs?
Click to know the detail about the - Latest Nodejs Version
11) Where To Downloads and Install?
The Latest LTS Version: 12.13.1 (includes npm 6.12.1)
Download the Node.js source code or a pre-built installer for your platform, and start developing today.
The Downloads link…
12) How To upgrading Node.js to latest version?
Windows:
You just download and reinstall node from the “.msi” in Windows from the node website.
Linux/Mac:
The module n makes version-management easy:
sudo npm install n -g
For the latest stable version:
sudo n stable
For the latest version:
sudo n latest
13) When Should We Use Node.js?
Nodejs can be used to develop:
1. Node used for general Purpose Applications
2. Node used for real-Time Web Applications
3. Node used for developing chat applications
4. Node used for developing network applications
5. Node used for developing game servers
6. Node used for distributed systems
14) When To Not Use Node.Js?
Node is a single threaded framework, so we should not use where the application requires long processing time, or taking so much time for any calculations.
15) For Node.js, Why Google uses V8 Engine?
Google uses V8 as it is a Chrome runtime engine that converts JavaScript code into native machine code.
These, in turn, speeds up the application execution and response process and give you a fast running application.
16) What Are the Features of Node.js?
The list of Node Features:
1. It is open source
2. High Scalability
3. It is extremely Simple and Fast
4. No Buffering
5. Single-Threaded
6. Asynchronous
7. Async stack traces
8. Faster await
9. Cross-Platform
10. Faster suite
11. Easy to Learn
12. Easy to Scale
13. Caching
14. Data Streaming
15. Hosting
16. Single Programming Language
17. Real-time web applications
18. import / export statements supported (no bundler required)
19. Faster parsing of JavaScript
20. Faster calls with arguments mismatch
21. And some other Improvements like - Heap Size, Native Modules N-API
22. License: It is been released under MIT license.
17) How To check the NPM version?
You can always check the version with following command:
npm -version
18) How To check the Node version?
You can always check the version with following command:
node –v
19) What modules that Nodejs offers?
Three modules that Nodejs offers:
1. Core Modules
2. Local Modules
3. Third-party modules
Core Modules -
Generally, Core modules get loaded just after the initiation of the Node process.
Local Modules -
The Local modules are created locally by the user or dedicated software developer. All such modules may have several functionalities grouped into different files and folders. And all these can be distributed in the Nodejs community with the help of Node Package Manager.
Third-party modules or External Modules -
The third-party modules by downloading them through Node Package Manager.
20) What Is Global Objects in Node.Js?
The term global objects standard built-in objects.
These objects are available in all modules. The following variables may appear to be global but are not. They exist only in the scope of modules, see the module system documentation:
1. __dirname
2. __filename
3. exports
4. module
5. require()
Note - most of developers to be confused with the global object.
21) What Is Value properties in Node.js?
The Value properties are global properties and it is returning a simple value; they have no properties or methods.
1. Infinity
2. NaN
3. undefined
4. null literal
5. globalThis
22) What Is Function properties in Node.js?
The function properties are global functions. These global functions—functions which are called globally rather than on an object—directly return their results to the caller.
1. eval()
2. uneval()
3. isFinite()
4. isNaN()
5. parseFloat()
6. parseInt()
7. decodeURI()
8. decodeURIComponent()
9. encodeURI()
10. encodeURIComponent()
11. escape()
12. unescape()
23) What Is Node.js' Cluster module?
The Nodejs module used to take advantage of multi-core systems, so that apps can handle more load.
24) What does package.json file consist of?
The metadata information in package.json file can be categorized into below categories:
1. Identifying metadata properties
2. Functional metadata properties
35) What is the file `package.json`?
The package.json is a plain JSON text file which contains all metadata information about Node JS Project or application.
Every Node JS Package/Module should have this file at root directory to describe its metadata in plain JSON Object format.
For a more complete package.json, we can check out-
{
"name": "npm-demo",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"bootstrap": "^4.3.1",
"jquery": "^3.4.1",
"popper.js": "^1.16.0",
"react": "^16.12.0",
"react-bootstrap": "^1.0.0-beta.15",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"description": "This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).",
"main": "index.js",
"devDependencies": {},
"repository": {
"type": "git",
"url": "demo"
},
"keywords": [
"npm-demo"
],
"author": "Anil",
"license": "ISC"
}
The detail about:
· name: The name of the application/project.
· version: The version of application.
· description: The describe about your application
· main: This is the entry/starting point of the app.
· scripts: The scripts which needs to be included in the application to run properly.
· engines: The versions of the node and npm used.
· keywords: It specifies the array of strings that characterizes the application.
· author: It consist of the name of the author
· license: The license of the application if applicable
· dependencies: Installed third party package using npm information
· devDependencies: The dependencies that are used only in the application development like GIT.
· repository: It contain the information about the type and url of the repository where application is host application
26) Who uses package.json file?
NPM (Node Package Manager) uses this package.json file information about Node application information or Node Package details.
The package.json file contains a number of different directives or elements.
27) What is the alternative to the Node package manager (npm), which was introduced by Facebook in 2016?
yarn
28) What Is the difference between dependencies and devDependencies?
Both are defined in the package.json.
The Dependencies list the packages that the project is dependent on.
The devDependencies list the dependencies which are only required during testing and development.
29) What Directives is required in package.json file?
The Package.json file contains two mandatory directives -
1. name
2. version
Name - The name is a mandatory directive in package.json file and it is a unique package/module name.
Version - The Version is a mandatory directive in package.json file and it contains the version information.
30) What Is control flow function?
A generic piece of code which runs in between several asynchronous function calls is known as control flow function.
31) What Is a Blocking function?
A blocking function's execution must be completed before other statements are executed.
32) What Is the difference between Angular and Node.js?
Angular -
1. Angular is an open source web application development frameworks and It is written in TypeScript.
2. Angular is used for creating highly active and interactive single page applications.
3. Angular is very helpful in splitting an app into MVC components.
Node.js -
1. Node is a cross-platform run-time environment for applications and It is written in C, C++ and JavaScript languages.
2. Node used for building a fast and scalable, and server side networking applications.
3. Node is very helpful in generating database queries.
33) How many types of API functions are there in Node.js?
There are two types of API functions in Node.js:
1. Asynchronous, non-blocking functions
2. Synchronous, blocking functions
34) What Are Async and Await?
A function marked with the async keyword can contain an await expression.
The await expression pauses the execution of the function and waits for the resolution of the passed Promise. It then resumes the function's execution and returns the resolved value.
35) Is Node.js really Single-Threaded?
Yes, it is a single thread
36) Does Node.js operate in a single-threaded or multi-threaded fashion?
Node.js operates on a single thread.
37) What Is the event loop?
The Node.js processes incoming requests in the event loop. It is what allows Node.js to perform non-blocking operations despite the fact that JavaScript is single-threaded.
38) What Is __dirname?
A global variable which returns the absolute path of the directory containing the currently executing file.
39) What IS the difference between setImmediate and setTimeout?
The setImmediate is used to run a function once the current event loop completes.
The setTimeout is used to run a function after a certain minimal timeout.
40) Explain REPL in the context of Node.js?
REPL stands for Read, Eval, Print, and Loop.
REPL represents a computer environment such as a window console or Unix/Linux shell where any command can be entered and then the system can respond with an output.
Node.js comes bundled with a REPL environment by default.
REPL can perform the below-listed tasks:
1. Read: Reads the user’s input, parses it into JavaScript data-structure and then stores it in the memory.
2. Eval: It used for receives and evaluates the data structure.
3. Print: Prints used for print the final result.
4. Loop: It used for loops the provided command until CTRL+C is pressed twice.
41) What Is callback?
A callback is an asynchronous function which is being called when an Ajax request/call is completed.
The Node.js is using much more callback because the entire node APIs use it.
42) What is “Error First Callback” in Node.js?
The “Error first callback” is used to pass an error and data. The first argument to these functions is an error object and the second argument represents to the success data. So, you can check the first argument as an error object and the second argument as data. If nothing wrong happen in your app use data.
As an Example,
var successCallback = function (callback) {
this._get(function (error, data) {
if (error) {
console.log(error);
return;
} else {
callback(null, data);
}
});
};
The error first callback pattern just requires that your function accepted two parameters and the first is an error and second one is the data.
The error is an object not a function and the error object containing the related information an also we can set a null value at the place of error object if there is no error occurred in the apps.
Summary,
Only Two Rules for defining an error first callback,
1. The first argument of the callback is reserved for an error object.
2. The second argument of the callback is reserved for response data (this is only for successful response).
43) How can you avoid callback hells?
To do so you have more options:
1. modularization: break callbacks into independent functions
2. Use promise
3. Use yield with Generators and/or Promises
44) What Are promises?
A Promise is a value returned by an asynchronous function to indicate the completion of the processing carried out by the asynchronous function.
Promises can be nested within each other to make code look better and easier to maintain when an asynchronous function need to be called after another asynchronous function.
45) What Is underscore in Node.js?
The Underscore is a library that is used to deal with arrays, collections and objects in JavaScript.
Underscore.js can be added to a Node.js application using NPM commands-
> npm install underscore
Once added, underscore can be referred in any of the Node.js modules using the CommonJS syntax:
var _ = require('underscore');
As an Example,
demo/js/node_underscore.js –
var numbers = [1, 2, 5, -3];
var squares = _.map(numbers, function (n) {
return n * n;
});
console.log(squares);
And run it node node_underscore.js -
The output Is - [1, 4, 25, 9]
46) What Is LTS releases of Node.js?
The LTS stands Long Term Support version of Node.js that receives all the critical bug fixes along with security updates and performance improvements.
47) What Is the concept of stub in Node.js?
The stubs are basically the programs or functions that are used for stimulating the module or component behavior.
48) What Are the various Timing Features of Node.js?
Node.js provides a Timers module which contains various functions for executing the code after a specified period of time.
The list of Timers modules:
1. setTimeout/clearTimeout
2. setInterval/clearInterval
3. setImmediate/clearImmediate
4. process.nextTick
49) What Are the difference between node.js and Ajax?
Node.js is a server-side JavaScript-based technology and it’s used for developing the server software that are typically executed by the servers instead of the web browsers.
AJAX is a client-side JavaScript-based technology and it’s mostly used for updating or modifying the webpage contents without having to refresh it.
50) Does Node.js provide any Debugger?
Yes! It is.
Syntax: node debug [script.js | -e "script" | <host> : <port> ]
51) What Is Stream and Explain types?
Streams are a collection of data that might not be available all at once and don’t have to fit in memory. Streams provide chunks of data in a continuous manner. It is useful to read a large set of data and process it.
Four type of streams:
1. Readable
2. Writeable
3. Duplex
4. Transform
52) List types of Http requests in Node.js?
Http defines a set of request methods to perform the desired actions.
These request methods are:
GET: The GET method asked for the representation of the specified resource and used to for retrieve the data.
POST: The POST technique is utilized to present an element to the predetermined resource, generally causing a change in state or reactions on the server.
HEAD: The HEAD method is similar to the GET method but asks for the response without the response body.
PUT: This method is used to substitute all current representations with the payload.
DELETE: It is used to delete the predetermined resource.
CONNECT: This request is used to settle the TCP/IP tunnel to the server by the target resource
OPTION: This method is used to give back the HTTP strategies to communicate with the target resource.
TRACE: This method echoes the message which tells the customer how much progressions have been made by an intermediate server.
PATCH: The PATCH method gives partial modifications to a resource.
53) How To enable CORS on Node.js?
As an Example,
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
54) How Node.js Read the Content of a file?
Node provides the fs library to handle file-system related operations. The fs.readFile() method is used to read files on your computer.
The common use for the File System module:
1. Read files
2. Create files
3. Update files
4. Delete files
5. Rename files
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.
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.
As an example to active this –
Read file in asynchronously (non-blocking) -
var fs = require('fs');
fs.readFile('filePath', 'utf8', function (err, contents) {
console.log(contents);
});
console.log('after calling readFile');
Read file in synchronously (blocking) -
var fs = require('fs');
var contents = fs.readFileSync('filePath', 'utf8');
console.log(contents);
55) How To Read a text file using Node.js?
The fs.readFile() method is used to read files on your computer.
As an Example,
var fs = require('fs');
try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
}
catch (e) {
console.log('Error:', e.stack);
}
56) How To Read a HTML file using Node.js?
The fs.readFile() method is used to read files on your computer.
As an Example,
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
}).listen(8080);
Note - If you don't specify an encoding for fs.readFile, you will retrieve the raw buffer instead of the expected file contents.
57) What Are the exit codes in Node.js?
Exit codes are specific codes that are used to end a process.
1. Unused
2. Uncaught Fatal Exception
3. Fatal Error
4. Non-function Internal Exception Handler
5. Internal Exception handler Run-Time Failure
6. Internal JavaScript Evaluation Failure
58) Can you access DOM in node?
No, you cannot access DOM in node.
59) How to run multiple Node.js files?
You can run multiple node.js files on a same server. Launching each with node my_file.js.
60) How to check the file size in node.js?
Try the ways to get –
var fs = require("fs"); //Load the file system module
var stats = fs.statSync("myfile.txt")
var fileSizeInBytes = stats["size"]
//Convert the file size to megabytes (optional)
var fileSizeInMegabytes = fileSizeInBytes / 1000000.0;
console.log(fileSizeInMegabytes);
OR
var getFilesizeInBytes = function (file_name) {
var stats = fs.statSync(file_name)
var fileSizeInBytes = stats["size"];
return fileSizeInBytes
}
61) How to create log file in Node.js?
The Winston is a very-popular npm-module used for logging.
Install Winston in your project as:
> npm install winston --save
Here's a configuration ready to use out-of-box that I use frequently in my projects as logger.js under until.
/* Configurations of logger. */
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
const consoleConfig = [
new winston.transports.Console({
'colorize': true
})
];
const createLogger = new winston.Logger({
'transports': consoleConfig
});
const successLogger = createLogger;
successLogger.add(winstonRotator, {
'name': 'access-file',
'level': 'info',
'filename': './logs/access.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
const errorLogger = createLogger;
errorLogger.add(winstonRotator, {
'name': 'error-file',
'level': 'error',
'filename': './logs/error.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
module.exports = {
'successlog': successLogger,
'errorlog': errorLogger
};
And then simply import wherever required as this:
const errorLog = require('../util/logger').errorlog;
const successlog = require('../util/logger').successlog;
Then you can log the success as:
successlog.info(`Success Message and variables: ${variable}`);
You can log the errors as:
errorlog.error(`Error Message : ${error}`);
You can see the logs success-logs and error-logs in a file under logs directory date.
62) How to call function from another file in Node.js?
See the example in below link,
See the example in below link,
https://evdokimovm.github.io/javascript/nodejs/2016/06/13/NodeJS-How-to-Use-Functions-from-Another-File-using-module-exports.html
63) Why Node.js is more popular than Ruby on Rails and other alternatives?
Node.js has ability to handle the thousands of concurrent connections with single process and minimum overhead using the JavaScript developed the server applications and networking applications.
There are some reasons which people choose Node.js.
I. Streaming Data
II. A real time applications like online games, collaboration tools and chat rooms etc.
III. Great Performance in I/O Processing
IV. JSON APIs based Applications
V. PROXY Applications
VI. Node.js is developed with Google's JavaScript V8 engine as its core.
However, there are some inconveniences of the Node.js language which may stay forever:
I. Nested callback hell.
II. In Node.js, any CPU intensive computation will block the responsiveness.
III. Dealing with files can be a bit of a pain.
IV. In Node.js, the relational database is a bit of a pain.
V. It's asynchronous programming model not for synchronous model.
Finally, we can say that Node.js is good in some cases but it cannot takeover Ruby on Rails because,
I. Ruby on Rails is a web framework.
II. Node.js is a server-side JavaScript implementation.
64) What Is EventEmitter in Node.js?
In Node.js, EventEmitter is use to “emit” an errors and also when your object emits lots of types of events.
There are multiple objects that inherit from EventEmitter and the “error” events emitted in Node objects looks like,
1. Streams
2. Servers
3. Requests and Responses
4. Child Processes etc.
As an Example,
//EventEmitter to “emit” errors.
var emitr = new (require('events').EventEmitter)();
//Calling asyncEmitter method.
var event = asyncEmitter();
//This method is called, when an "error" event is emitted!
event.on("error", function(error) {
console.error(error);
//console.trace(error);
});
// This is used to emits the "error" event and return it.
var asyncEmitter = function() {
process.nextTick(function(){
emitr.emit("error", new Error("Here something went wrong!"));
});
return emitr;
};
The EventEmitter will help you all to write the event based Node modules and also your knowledge of EventEmitter will greatly affect your efficiency Node.js carrier.