feat: add Node.js questions (#5056)
* feat: add nodejs questions * feat: add more questionspull/5075/head
parent
ed0e376d46
commit
747652c0f3
9 changed files with 409 additions and 0 deletions
@ -0,0 +1,17 @@ |
||||
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. |
||||
|
||||
## CommonJS |
||||
|
||||
```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. |
||||
|
||||
## ES 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. |
@ -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); |
||||
}); |
||||
``` |
@ -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 |
@ -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); |
||||
}); |
||||
``` |
@ -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. |
@ -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 |
||||
// ] |
||||
``` |
@ -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 |
||||
``` |
@ -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/'); |
||||
}); |
||||
``` |
@ -0,0 +1,227 @@ |
||||
--- |
||||
order: 1 |
||||
briefTitle: 'Node.js' |
||||
briefDescription: 'Test, rate and improve your Node.js knowledge with these questions.' |
||||
title: 'Node.js Questions' |
||||
description: 'Curated list of Node.js questions to test, rate and improve your knowledge. Questions are based on real world experience and knowledge.' |
||||
isNew: true |
||||
seo: |
||||
title: 'Node.js Questions' |
||||
description: 'Curated list of Node.js questions to test, rate and improve your knowledge. Questions are based on real world experience and knowledge.' |
||||
keywords: |
||||
- 'node.js quiz' |
||||
- 'node.js questions' |
||||
- 'node.js interview questions' |
||||
- 'node.js interview' |
||||
- 'node.js test' |
||||
sitemap: |
||||
priority: 1 |
||||
changefreq: 'monthly' |
||||
questions: |
||||
- question: What is Node.js? |
||||
answer: 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. |
||||
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: |
||||
- 'Core' |
||||
- 'Beginner' |
||||
- question: What is Event Loop in Node.js? |
||||
answer: | |
||||
The event loop is a single-threaded loop responsible for handling all asynchronous callbacks 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. |
||||
topics: |
||||
- 'Core' |
||||
- 'Intermediate' |
||||
- question: What is the difference between Node.js and AJAX? |
||||
answer: | |
||||
Node.js is a server-side runtime for JavaScript, while AJAX is a client-side technique for asynchronous communication with the server. |
||||
topics: |
||||
- 'Core' |
||||
- 'Beginner' |
||||
- question: What are modules in Node.js? |
||||
answer: | |
||||
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. |
||||
topics: |
||||
- 'Core' |
||||
- 'Beginner' |
||||
- question: Difference between CommonJS and ESM? |
||||
answer: commonjs-vs-esm.md |
||||
topics: |
||||
- 'Core' |
||||
- 'Intermediate' |
||||
- question: What is the `global` object in Node.js? |
||||
answer: | |
||||
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. |
||||
topics: |
||||
- 'Core' |
||||
- 'Intermediate' |
||||
- question: What is the difference between `process.nextTick()` and `setImmediate()`? |
||||
answer: | |
||||
`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. |
||||
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 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: | |
||||
`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' |
||||
--- |
Loading…
Reference in new issue