Node.js Questions

Kamran AhmedKamran Ahmed

Test yourself with Flashcards

You can either use these flashcards or jump to the questions list section below to see them in a list format.

0 / 36
Knew0 ItemsLearnt0 ItemsSkipped0 Items

What is Node.js?

Node.js is an open-source and cross-platform JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Questions List

If you prefer to see the questions in a list format, you can find them below.

Core

What is Node.js?

Node.js is an open-source and cross-platform JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

What is REPL in Node.js?

REPL stands for Read-Eval-Print-Loop. It is an interactive shell that allows you to execute JavaScript code and view the output immediately. It is useful for testing small snippets of code and experimenting with the Node.js API.

What is the difference between Node.js and JavaScript?

Node.js is a runtime environment for JavaScript. JavaScript is a programming language used to create web applications. Node.js is a runtime environment that can execute JavaScript code outside of a web browser.

What is Event Loop in Node.js?

The event loop is a single-threaded loop responsible for handling all asynchronous tasks in Node.js. It continuously checks for events and executes associated callback functions, allowing Node.js to handle asynchronous tasks efficiently. Its non-blocking I/O model ensures that it can process multiple operations simultaneously without waiting for one to complete before moving on to the next, contributing to its scalability and performance. Watch this video to learn more about the topic.

What is the difference between Node.js and AJAX?

Node.js is a server-side runtime for JavaScript, while AJAX is a client-side technique for asynchronous communication with the server.

What are modules in Node.js?

Modules are reusable blocks of code that can be imported into other files. They are used to encapsulate related code into a single unit of code that can be used in other parts of the program. It allow us to split our code into multiple files and reuse it across multiple files. Some built-in modules include fs, http, path, url, util, etc.

Difference between CommonJS and ESM?

CommonJS and ES Modules are two different module systems in JavaScript. CommonJS is the module system used in Node.js, while ES Modules are the module system used in browsers and TypeScript.

js
const fs = require('fs');

CommonJS modules are loaded synchronously. This means that the module is loaded and evaluated before the code using the module is executed. It uses require() to load modules and module.exports to export modules.

js
import fs from 'fs';

ES Modules are loaded asynchronously. This means that the module is loaded and evaluated when the module is used. It uses import to load modules and export to export modules.

ES Modules

What is the global object in Node.js?

The global object is a global namespace object that contains all global variables, functions, and objects. It is similar to the window object in the browser. It can be accessed from anywhere in the program without importing it.

What is the difference between process.nextTick() and setImmediate()?

process.nextTick() and setImmediate() are both used to schedule a callback function to be executed in the next iteration of the event loop. The difference is that process.nextTick() executes the callback at the end of the current iteration of the event loop, while setImmediate() executes the callback at the beginning of the next iteration of the event loop.

What is setInterval()?

setInterval() is a global function that helps you execute a function repeatedly at a fixed delay. It returns an interval ID that uniquely identifies the interval, which can be used to cancel the interval using the clearInterval() function.

What is setTimeout()?

setTimeout() is a global function that helps you execute a function after a specified delay. It returns a timeout ID that uniquely identifies the timeout, which can be used to cancel the timeout using the clearTimeout() function.

What are Event Emitters in Node.js?

Event Emitters is a class that can be used to emit named events and register listeners for those events. It is used to handle asynchronous events in Node.js.

What is npm?

npm is a package manager for Node.js. It is used to install, update, and remove packages from the Node.js ecosystem. It is also used to manage dependencies for Node.js projects.

What is the full form of npm?

npm stands for Node Package Manager.

What is npx?

npx is a tool that allows you to run Node.js packages without installing them. It is used to execute Node.js packages that are not installed globally.

What is process.cwd()?

process.cwd() returns the current working directory of the Node.js process. It is similar to pwd in Unix.

What is the difference between process.cwd() and __dirname?

process.cwd() returns the current working directory of the Node.js process, while __dirname returns the directory name of the current module.

js
console.log(process.cwd());// /Users/username/projects/nodejsconsole.log(__dirname);// /Users/username/projects/nodejs/src

What is __filename?

__filename is a global variable that contains the absolute path of the current file.

What is process.argv?

process.argv is an array containing the command-line arguments passed when the Node.js process was launched. The first element is the path to the Node.js executable, the second element is the path to the JavaScript file being executed, and the remaining elements are the command-line arguments.

js
node index.js hello world
js
console.log(process.argv);// [//   '/usr/local/bin/node', -> path to the Node.js executable//   '/Users/username/projects/nodejs/index.js', -> path to the JavaScript file being executed//   'hello', -> command-line argument//   'world' -> command-line argument// ]

What is the purpose of fs module?

The File System (fs) module is used to perform file operations such as reading, writing, and deleting files. All file system operations have synchronous and asynchronous forms.

What is the purpose of path module?

The Path module is used to perform operations on file and directory paths. It provides methods for resolving and normalizing paths, joining paths, and extracting file and directory names.

How to read a file in Node.js?

The fs.readFile() method is used to read the contents of a file asynchronously. It takes the path of the file to be read and a callback function as arguments. The callback function is called with two arguments, err and data. If an error occurs while reading the file, the err argument will contain the error object. Otherwise, the data argument will contain the contents of the file.

How to load environment variables from a .env file in Node.js?

The dotenv package is used to load environment variables from a .env file into process.env. It is used to store sensitive information such as API keys, database credentials, etc. in a .env file instead of hardcoding them in the source code.

How to access environment variables in Node.js?

Environment variables can be accessed using the process.env object. It is an object that contains all the environment variables defined in the current process.

How to create a web server in Node.js?

To create a minimal Hello, World! HTTP server in Node.js, you can use the http module. It provides an HTTP server, and the createServer() method sets up a server instance with a callback function to handle incoming requests

js
import http from 'node:http';const server = http.createServer((req, res) => {  res.writeHead(200, { 'Content-Type': 'text/plain' });  res.end('Hello World\n');});server.listen(3000, () => {  console.log('Server running at http://localhost:3000/');});

What are streams in Node.js?

Streams are objects that allow you to read data from a source or write data to a destination in a continuous manner. They are used to handle large amounts of data efficiently.

What is difference between fork and spawn methods of child_process module?

The fork method is used when you want to run another JavaScript file in a separate worker. It's like having a friend with a specific task. You can communicate with them via messages and they can send messages back to you. The spawn method is used when you want to run a command in a separate process. It's like asking someone to do a specific. You can communicate with them via stdin/stdout/stderr, but it's more like giving orders and getting results.

What is the os module?

The os module provides methods for interacting with the operating system. It can be used to get information about the operating system, such as the hostname, platform, architecture, etc.

Can you access the DOM in Node.js?

No, you cannot access the DOM in Node.js because it does not have a DOM. It is a server-side runtime for JavaScript, so it does not have access to the browser's DOM.

What is Clustering in Node.js?

Clustering is a technique used to distribute the load across multiple processes. It is used to improve the performance and scalability of Node.js applications.

How can memory leaks happen in Node.js?

Memory leaks happen when a program allocates memory but does not release it when it is no longer needed. This can happen due to bugs in the program or due to the way the program is designed. In Node.js, memory leaks can happen due to the use of closures, circular references, and global variables.

What is the order priority of process.nextTick, Promise, setTimeout, and setImmediate?

Order priorities of process.nextTick, Promise, setTimeout and setImmediate are as follows:

  1. process.nextTick: Highest priority, executed immediately after the current event loop cycle, before any other I/O events or timers.

  2. Promise: Executed in the microtask queue, after the current event loop cycle, but before the next one.

  3. setTimeout: Executed in the timer queue, after the current event loop cycle, with a minimum delay specified in milliseconds.

  4. setImmediate: Executed in the check queue, but its order may vary based on the system and load. It generally runs in the next iteration of the event loop after I/O events.

js
console.log('start');Promise.resolve().then(() => console.log('Promise'));setTimeout(() => console.log('setTimeout'), 0);process.nextTick(() => console.log('process.nextTick'));setImmediate(() => console.log('setImmediate'));console.log('end');// Output:// start// end// process.nextTick// Promise// setTimeout// setImmediate

In summary, the order of execution is generally process.nextTick > Promise > setTimeout > setImmediate. However, keep in mind that the behavior may vary in specific situations, and the order might be influenced by factors such as system load and other concurrent operations.

What is process.exit()?

process.exit() is a method that can be used to exit the current process. It takes an optional exit code as an argument. If no exit code is specified, it defaults to 0.

Different exit codes in Node.js?

The following exit codes are used in Node.js:

  • 0: Success

  • 1: Uncaught Fatal Exception

  • 2: Unused

  • 3: Internal JavaScript Parse Error

  • 4: Internal JavaScript Evaluation Failure

  • 5: Fatal Error

  • 6: Non-function Internal Exception Handler

  • 7: Internal Exception Handler Run-Time Failure

  • 8: Unused

  • 9: Invalid Argument

  • 10: Internal JavaScript Run-Time Failure

  • 12: Invalid Debug Argument

  • 13: Uncaught Exception

  • 14: Unhandled Promise Rejection

  • 15: Fatal Exception

  • 16: Signal Exits

How Node.js handle errors?

There are four fundamental strategies to report errors in Node.js:

try...catch blocks are the most basic way to handle errors in JavaScript. They are synchronous and can only be used to handle errors in synchronous code. They are not suitable for asynchronous code, such as callbacks and promises.

js
import fs from 'node:fs';try {  const data = fs.readFileSync('file.md', 'utf-8');  console.log(data);} catch (err) {  console.error(err);}

Callbacks are the most common way to handle errors in asynchronous code. They are passed as the last argument to a function and are called when the function completes or fails.

js
import fs from 'node:fs';fs.readFile('file.md', 'utf-8', (err, data) => {  if (err) {    console.error(err);    return;  }  console.log(data);});

Promises are a more modern way to handle errors in asynchronous code. They are returned by functions and can be chained together. They are resolved when the function completes and rejected when it fails.

js
import fs from 'node:fs/promises';fs.readFile('file.md', 'utf-8')  .then((data) => {    console.log(data);  })  .catch((err) => {    console.error(err);  });

Event emitters are a more advanced way to handle errors in asynchronous code. They are returned by functions and emit an error event when they fail. They are resolved when the function completes and rejected when it fails.

js
import fs from 'node:fs';const reader = fs.createReadStream('file.md', 'utf-8');reader.on('data', (data) => {  console.log(data);});reader.on('error', (err) => {  console.error(err);});

CLI

How to take user input from the command line in Node.js?

In order to take user input from the command line, you can use the readline module. It provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.

js
import readline from 'node:readline';import { stdin as input, stdout as output } from 'node:process';const rl = readline.createInterface({ input, output });rl.question('What do you think of Node.js? ', (answer) => {  console.log(`Thank you for your valuable feedback: ${answer}`);  rl.close();});rl.on('close', () => {  console.log('\nBYE BYE !!!');  process.exit(0);});

Join the Community

search.highfps.fun is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank 6th out of 28M!

224K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+2.1M

Registered Users

Register yourself
Commit to your growth

+2kevery month

39K

Discord Members

Join on Discord
Join the community

RoadmapsBest PracticesGuidesVideosFAQsYouTube

search.highfps.funby@kamrify

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© search.highfps.fun·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.