diff --git a/src/data/question-groups/nodejs/content/error-handling.md b/src/data/question-groups/nodejs/content/error-handling.md new file mode 100644 index 000000000..269e06690 --- /dev/null +++ b/src/data/question-groups/nodejs/content/error-handling.md @@ -0,0 +1,66 @@ +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. + +```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); +}); +``` diff --git a/src/data/question-groups/nodejs/content/exit-codes.md b/src/data/question-groups/nodejs/content/exit-codes.md new file mode 100644 index 000000000..f544b60ab --- /dev/null +++ b/src/data/question-groups/nodejs/content/exit-codes.md @@ -0,0 +1,18 @@ +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 diff --git a/src/data/question-groups/nodejs/content/input-from-command-line.md b/src/data/question-groups/nodejs/content/input-from-command-line.md new file mode 100644 index 000000000..db6137f22 --- /dev/null +++ b/src/data/question-groups/nodejs/content/input-from-command-line.md @@ -0,0 +1,18 @@ +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); +}); +``` diff --git a/src/data/question-groups/nodejs/content/order-priority.md b/src/data/question-groups/nodejs/content/order-priority.md new file mode 100644 index 000000000..2a07b207e --- /dev/null +++ b/src/data/question-groups/nodejs/content/order-priority.md @@ -0,0 +1,25 @@ +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. diff --git a/src/data/question-groups/nodejs/content/process-argv.md b/src/data/question-groups/nodejs/content/process-argv.md new file mode 100644 index 000000000..c5559c1a1 --- /dev/null +++ b/src/data/question-groups/nodejs/content/process-argv.md @@ -0,0 +1,15 @@ +`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 +// ] +``` diff --git a/src/data/question-groups/nodejs/content/process-cwd-vs-dirname.md b/src/data/question-groups/nodejs/content/process-cwd-vs-dirname.md new file mode 100644 index 000000000..740698f3b --- /dev/null +++ b/src/data/question-groups/nodejs/content/process-cwd-vs-dirname.md @@ -0,0 +1,9 @@ +`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/nodejs + +console.log(__dirname); +// /Users/username/projects/nodejs/src +``` diff --git a/src/data/question-groups/nodejs/content/web-server.md b/src/data/question-groups/nodejs/content/web-server.md new file mode 100644 index 000000000..06a208e61 --- /dev/null +++ b/src/data/question-groups/nodejs/content/web-server.md @@ -0,0 +1,14 @@ +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/'); +}); +``` diff --git a/src/data/question-groups/nodejs/nodejs.md b/src/data/question-groups/nodejs/nodejs.md index f67edb48e..38b85f522 100644 --- a/src/data/question-groups/nodejs/nodejs.md +++ b/src/data/question-groups/nodejs/nodejs.md @@ -23,6 +23,12 @@ questions: topics: - 'Core' - 'Beginner' + - question: What is REPL in Node.js? + answer: | + 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. + topics: + - 'Core' + - 'Intermediate' + - question: Different exit codes in Node.js? + answer: exit-codes.md + topics: + - 'Core' + - 'Intermediate' + - question: How Node.js handle errors? + answer: error-handling.md topics: - 'Core' - 'Intermediate'