There are four fundamental strategies to report errors in Node.js:
## `try...catch` blocks
`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
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
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
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.
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';
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.
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.
`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
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
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.
topics:
- 'Core'
- 'Beginner'
- question: What is the difference between Node.js and JavaScript?
answer: 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.
topics:
@ -63,15 +69,158 @@ questions:
topics:
- 'Core'
- 'Intermediate'
- question: What is `setInterval()`?
answer: |
`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.
topics:
- 'Core'
- 'Beginner'
- question: What is `setTimeout()`?
answer: |
`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.
topics:
- 'Core'
- 'Beginner'
- question: What are Event Emitters in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Intermediate'
- question: What is `npm`?
answer: |
`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.
topics:
- 'Core'
- 'Beginner'
- question: What are Event Emitters in Node.js?
- question: What is the full form of `npm`?
answer: |
`npm` stands for Node Package Manager.
topics:
- 'Core'
- 'Beginner'
- question: What is `npx`?
answer: |
`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.
topics:
- 'Core'
- 'Beginner'
- question: What is `process.cwd()`?
answer: |
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. It is similar to the `EventTarget` interface in the browser.
`process.cwd()` returns the current working directory of the Node.js process. It is similar to `pwd` in Unix.
topics:
- 'Core'
- 'Intermediate'
- question: What is the difference between `process.cwd()` and `__dirname`?
answer: process-cwd-vs-dirname.md
topics:
- 'Core'
- 'Intermediate'
- question: What is `__filename`?
answer: |
`__filename` is a global variable that contains the absolute path of the current file.
topics:
- 'Core'
- 'Intermediate'
- question: What is `process.argv`?
answer: process-argv.md
topics:
- 'Core'
- 'Intermediate'
- question: What is the purpose of `fs` module?
answer: |
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.
topics:
- 'Core'
- 'Beginner'
- question: What is the purpose of `path` module?
answer: |
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.
topics:
- 'Core'
- 'Beginner'
- question: How to read a file in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Beginner'
- question: How to load environment variables from a `.env` file in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Beginner'
- question: How to access environment variables in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Beginner'
- question: How to take user input from the command line in Node.js?
answer: input-from-command-line.md
topics:
- 'Core'
- 'Beginner'
- question: How to create a web server in Node.js?
answer: web-server.md
topics:
- 'Core'
- 'Beginner'
- question: What are streams in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Intermediate'
- question: What is difference between `fork` and `spawn` methods of `child_process` module?
answer: |
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.
topics:
- 'Core'
- 'Intermediate'
- question: What is the `os` module?
answer: |
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.
topics:
- 'Core'
- 'Beginner'
- question: Can you access the DOM in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Intermediate'
- question: What is Clustering in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Intermediate'
- question: Why memory leak happens in Node.js?
answer: |
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.
topics:
- 'Core'
- 'Intermediate'
- question: What is the order priority of `process.nextTick`, `Promise`, `setTimeout`, and `setImmediate`?
answer: order-priority.md
topics:
- 'Core'
- 'Intermediate'
- question: What is `process.exit()`?
answer: |
`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.