Skip to content

Commit

Permalink
feat: add Node.js questions (kamranahmedse#5056)
Browse files Browse the repository at this point in the history
* feat: add nodejs questions

* feat: add more questions
  • Loading branch information
arikchakma committed Jan 22, 2024
1 parent ed0e376 commit 747652c
Show file tree
Hide file tree
Showing 9 changed files with 409 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/data/question-groups/nodejs/content/commonjs-vs-esm.md
Original file line number Diff line number Diff line change
@@ -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.
66 changes: 66 additions & 0 deletions src/data/question-groups/nodejs/content/error-handling.md
Original file line number Diff line number Diff line change
@@ -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);
});
```
18 changes: 18 additions & 0 deletions src/data/question-groups/nodejs/content/exit-codes.md
Original file line number Diff line number Diff line change
@@ -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
18 changes: 18 additions & 0 deletions src/data/question-groups/nodejs/content/input-from-command-line.md
Original file line number Diff line number Diff line change
@@ -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);
});
```
25 changes: 25 additions & 0 deletions src/data/question-groups/nodejs/content/order-priority.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions src/data/question-groups/nodejs/content/process-argv.md
Original file line number Diff line number Diff line change
@@ -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
// ]
```
Original file line number Diff line number Diff line change
@@ -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
```
14 changes: 14 additions & 0 deletions src/data/question-groups/nodejs/content/web-server.md
Original file line number Diff line number Diff line change
@@ -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:https://localhost:3000/');
});
```
Loading

0 comments on commit 747652c

Please sign in to comment.