Skip to content

Commit

Permalink
refactor: update files to maintain consistent text style, update irre…
Browse files Browse the repository at this point in the history
…levant links
  • Loading branch information
haslie22 committed Nov 18, 2023
1 parent 48f5a93 commit 0f50dec
Show file tree
Hide file tree
Showing 15 changed files with 77 additions and 70 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 5 additions & 5 deletions stage1/modules/node-materials/node/module/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ fs.writeFile(
(err) => {
if (err) throw err;
console.log("File was created");
}
},
);
```

Expand All @@ -57,7 +57,7 @@ fs.appendFile(
(err) => {
if (err) throw err;
console.log("File was modified");
}
},
);
```

Expand All @@ -73,7 +73,7 @@ fs.readFile(
(err, data) => {
if (err) throw err;
console.log(data);
}
},
);
```

Expand All @@ -89,10 +89,10 @@ fs.rename(
(err) => {
if (err) throw err;
console.log("File renamed");
}
},
);
```

### Project

[Note-taking Application](../projects/notes.md)
[Notes App](../projects/notes.md)
14 changes: 8 additions & 6 deletions stage1/modules/node-materials/node/module/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ This method takes a callback function `requestHandler` with two parameters, `req
- `request` holds information about the request
- `response` is responsible for sending the response

Our `requestHandler` logs the request method and the address of the requested resource to the console. It also sends the messages `Hello from Node.js` and `Bye!` as responses.
The `response.write()` method writes the message to the response body, and `response.end()` informs the server that the headers and body of the response are written and it can be sent.
Note that `response.end()` should terminate every response. Without it, the request processing will "hang" — the request will be received but not fully processed.
Our `requestHandler` logs the request method and the address of the requested resource to the console. It also sends the messages `Hello from Node.js` and `Bye!` as responses.

The `response.write()` method writes the message to the response body, and `response.end()` informs the server that the headers and body of the response are written and it can be sent.

Note that `response.end()` should terminate every response. Without it, the request processing will "hang" — the request will be received but not fully processed:

```js
const requestHandler = (request, response) => {
Expand All @@ -61,7 +63,7 @@ const requestHandler = (request, response) => {
};
```

The server's `listen` method starts it, and it begins to listen on the specified port for connections. It has multiple signatures; in our case, it takes three parameters: the local port, the local address, and a callback function that runs when it starts listening for connections.
The server's `listen` method starts it, and it begins to listen on the specified port for connections. It has multiple signatures; in our case, it takes three parameters: the local port, the local address, and a callback function that runs when it starts listening for connections:

```js
server.listen(PORT, "localhost", () => {
Expand All @@ -72,7 +74,7 @@ server.listen(PORT, "localhost", () => {
Run the file with the code, open your browser, and go to the address `localhost:3000/some/page`.
Note that to run the server with different code, you need to stop it and restart it. You already know how to terminate a Node.js process. Only one server can be running on a port at a time.

In the `write` and `end` methods, you can pass a string containing HTML tags with inline styles. These tags will be correctly processed by the browser.
In the `write` and `end` methods, you can pass a string containing HTML tags with inline styles. These tags will be correctly processed by the browser:

```js
const http = require("http");
Expand All @@ -99,4 +101,4 @@ By revisiting the page `localhost:3000/some/page`, you will see the rendered mar

## Project

[Github Application](../projects/github-app.md)
[Github App](../projects/github-app.md)
2 changes: 1 addition & 1 deletion stage1/modules/node-materials/node/module/npm-module.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

Let's install the `colors` module using `npm`. In the terminal, execute the command:

```powershell
```bash
npm install colors
```

Expand Down
50 changes: 28 additions & 22 deletions stage1/modules/node-materials/node/module/path.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,31 @@ You can find the information about the properties and methods of `path` in the [

Let's look at some of them:

- Retrieving file data
```js
// for a file located at C:\Users\Admin\Desktop\nodejs-basic\index.js
const path = require("path");
console.log(path.basename(__filename)); // index.js - file name on Windows, full file path on POSIX systems
console.log(path.dirname(__filename)); // C:\Users\Admin\Desktop\nodejs-basic - folder name
console.log(path.extname(__filename)); // .js - file extension
console.log(path.parse(__filename)); // returns an object specifying the disk root, folder name, file name, file extension, file name without extension
```
- Concatenating paths
```js
// for a file located at C:\Users\Admin\Desktop\nodejs-basic\index.js
const path = require("path");
// returns C:\Users\Admin\Desktop\nodejs-basic\test\second.html
console.log(path.join(__dirname, "test", "second.html"));
```
`path.join()` concatenates the specified path segments together, using the separator for the specific platform (forward slash `/` for Linux, backslash `\` for Windows). The result is a relative path.
```js
const path = require("path");
console.log(path.resolve(__dirname, "./test", "/second.html"));
```
`path.resolve()` converts a sequence of paths or path segments into an absolute path from right to left and normalizes it: if some path segments have slashes while others don't, it will still generate the correct path.
**Retrieving file data**

```js
// for a file located at C:\Users\Admin\Desktop\nodejs-basic\index.js
const path = require("path");
console.log(path.basename(__filename)); // index.js - file name on Windows, full file path on POSIX systems
console.log(path.dirname(__filename)); // C:\Users\Admin\Desktop\nodejs-basic - folder name
console.log(path.extname(__filename)); // .js - file extension
console.log(path.parse(__filename)); // returns an object specifying the disk root, folder name, file name, file extension, file name without extension
```

**Concatenating paths**

```js
// for a file located at C:\Users\Admin\Desktop\nodejs-basic\index.js
const path = require("path");
// returns C:\Users\Admin\Desktop\nodejs-basic\test\second.html
console.log(path.join(__dirname, "test", "second.html"));
```

`path.join()` concatenates the specified path segments together, using the separator for the specific platform (forward slash `/` for Linux, backslash `\` for Windows). The result is a relative path:

```js
const path = require("path");
console.log(path.resolve(__dirname, "./test", "/second.html"));
```

`path.resolve()` converts a sequence of paths or path segments into an absolute path from right to left and normalizes it: if some path segments have slashes while others don't, it will still generate the correct path.
10 changes: 5 additions & 5 deletions stage1/modules/node-materials/node/node-argv.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ The `process.argv.slice(2)` method returns a new array that starts from the elem

To have the ability to send arguments in any order or skip some of them, you can mark command line arguments. For this purpose, flags are used. Flags are words or symbols indicating that a command line argument follows them. Flags are usually preceded by one or two dashes to avoid confusion with arguments. For example:

```powershell
```bash
node test -m Hello
```

Expand Down Expand Up @@ -80,7 +80,7 @@ obj.sayHi();

with the option `--disable-proto=throw`:

```powershell
```bash
node --disable-proto=throw test
```

Expand Down Expand Up @@ -119,14 +119,14 @@ if (productionMode) {

Write a program that prompts the user to enter two numbers, adds these numbers if launched with the `-s` flag, or multiplies them if launched with the `-m` flag, and then terminates. Use standard input/output for input and output. Here is an example of how it should work (user input starts with `>`):

```powershell
```bash
> node test.js -m
Enter 2 numbers
> 2 7
2 * 7 = 14
```

```powershell
```bash
> node test.js -s
Enter 2 numbers
> 2 7
Expand All @@ -150,7 +150,7 @@ stdin.on("data", (data) => {
const numStringsArray = numString.split(" ");
const hasIncorrectLength = numStringsArray.length !== 2;
const hasIncorrectValues = numStringsArray.some((numStr) =>
Number.isNaN(+numStr)
Number.isNaN(+numStr),
);
if (hasIncorrectLength || hasIncorrectValues) {
stdout.write("You need to enter 2 numbers separated by a space");
Expand Down
2 changes: 1 addition & 1 deletion stage1/modules/node-materials/node/node-fs-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ console.log(__dirname);

Open the terminal and run the file:

```powershell
```bash
node test
```

Expand Down
4 changes: 2 additions & 2 deletions stage1/modules/node-materials/node/node-introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

### Installing Node.js

Download link https://nodejs.org/en
Download link: https://nodejs.org/en

Download and install the latest LTS version (Recommended For Most Users)

Expand Down Expand Up @@ -54,7 +54,7 @@ console.log("Hello, world!");

Open this file with VS Code, in the terminal execute the command:

```powershell
```bash
node test.js
```

Expand Down
7 changes: 4 additions & 3 deletions stage1/modules/node-materials/node/node-module.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Packages are convenient to work with using package managers such as `npm` or `ya

To install a package using `npm`, use the command:

```powershell
```bash
npm install <module name>
```

Expand All @@ -76,7 +76,7 @@ A `package.json` file is created in the project folder, describing the created a

### Installing Packages via npm

To install a module, use the command
To install a module, use the command:

```bash
npm install <module name>
Expand All @@ -94,7 +94,8 @@ Removing a module:
npm uninstall nodemon
```

Installed modules are added to the `node_modules` folder, and information about them is added to the `package.json` file. Additionally, a `package-lock.json` file is automatically created, ensuring package identity among different users and performing other useful functions.
Installed modules are added to the `node_modules` folder, and information about them is added to the `package.json` file.
Additionally, a `package-lock.json` file is automatically created, ensuring package identity among different users and performing other useful functions.

If you delete the `node_modules` folder and execute the `npm install` command, the `node_modules` folder will be restored along with all the added modules based on the records in the `package.json` file.

Expand Down
2 changes: 1 addition & 1 deletion stage1/modules/node-materials/node/node-stdio.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ stdin.on("data", (data) => {
});
```

If we log the type of the `data` variable to the console, we will see `object`. By applying the [trick with the special `[[Class]]` property](https://learn.javascript.ru/class-instanceof#sekretnoe-svoystvo-class), we get `[object Uint8Array]` for `data`.
If we log the type of the `data` variable to the console, we will see `object`. By applying the [trick with the toString() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString#using_tostring_to_detect_object_class), we get `[object Uint8Array]` for `data`.

Since `process.stdin` is a stream, it works with data in **binary** format. To handle such data in Node.js, there is a special `Buffer` object, which is a subclass of `Uint8Array` (a typed array storing 8-bit unsigned integer values).
The data contained in the `Buffer` can be converted to a string:
Expand Down
21 changes: 13 additions & 8 deletions stage1/modules/node-materials/node/projects/github-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ To achieve this, we'll use the GitHub API. The request `https://api.github.com/u

1. Start by creating a new Node.js application

Create a folder named github-app, open it in VS Code, and run the following command in the terminal:
Create a folder named `github-app`, open it in VS Code, and run the following command in the terminal:

```
npm init -y
Expand All @@ -35,6 +35,7 @@ const username = process.argv[2];

Use the imported `github` object, which has a `getRepos()` property - a function that returns a list of user repositories.
The parameters of the `getRepos()` function are `username` - the username and a callback function taking two parameters: `error` - an error, and `repos` - the received data, in our case, a list of repositories.

In the callback function, let's handle the error and print the names of the repositories to the console:

```js
Expand All @@ -49,11 +50,11 @@ github.getRepos(username, (error, repos) => {

Our application will communicate with the server over the `https` protocol. For this, Node.js has a built-in `https module`, similar to the [HTTP Module](../module/http.md).

To send a request to the API, we'll use the `get()` method, which allows us to retrieve data from the server.
To send a request to the API, we'll use the `get()` method, which allows us to retrieve data from the server.
Import the `https` module and write the code for the `getRepos()` function. The function parameter is `username` - the GitHub username.
The `https.get()` method has two parameters: the URL to which the request is sent and a callback function taking one parameter - the server response, abbreviated as `res`.

The `res.statusCode` property returns the server response. A response of `200` indicates a successful connection, while any other response indicates a connection problem.
The `res.statusCode` property returns the server response. A response of `200` indicates a successful connection, while any other response indicates a connection problem.
Export the `github` module as an object with a `getRepos` property and the value of `getRepos`:

```js
Expand Down Expand Up @@ -94,7 +95,8 @@ Use the `option` object as the first parameter in `the https.get` method. The ap

4. Handling incoming data

Almost everything in Node.js, including communication with the server, is implemented asynchronously, using events and streams. Information from the server comes in parts.
Almost everything in Node.js, including communication with the server, is implemented asynchronously, using events and streams. Information from the server comes in parts.

The server response (`res`) has a `data` event, which fires when a part of the requested information comes from the server. Subscribe to this event and print the received data to the console:

```js
Expand Down Expand Up @@ -133,7 +135,8 @@ function getRepos(username) {
}
```

The response (`res`) method has an `end` event, which triggers when the data transmission is complete.
The response (`res`) method has an `end` event, which triggers when the data transmission is complete.

Upon the occurrence of this event, use the `JSON.parse(body)` method to convert the received data into an array:

```js
Expand Down Expand Up @@ -186,6 +189,8 @@ function getRepos(username, done) {

6. Error Handling

When working with the application, errors may occur in the following cases:

- The application is launched without a username
- An error occurs when sending a request if a nonexistent username is specified
- An error occurs when receiving a response from the server
Expand All @@ -199,7 +204,7 @@ Handle errors in the `github` module and pass them to the `app` module, specifyi
if (!username) return done(new Error("Username is required"));
```

2. Request error - the `error` event of the `request` method.
2. Request error - the `error` event of the `request` method

Create a variable `request` and set its value to the `https.get()` method:

Expand Down Expand Up @@ -253,8 +258,8 @@ function getRepos(username, done) {
} else {
done(
new Error(
`Error working with the server ${res.statusCode} ${res.statusMessage}`
)
`Error working with the server ${res.statusCode} ${res.statusMessage}`,
),
);
}
});
Expand Down
17 changes: 6 additions & 11 deletions stage1/modules/node-materials/node/projects/notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

[HOME](../../README.md)

Let's write a simple console application called Notes for working with notes. The application needs to implement four methods:
Let's write a simple console application called Notes for working with notes. The application needs to implement 4 methods:

- `create`
- `list`
- `view`
- `remove`

The `create` method creates a new note in the notes.json file. The `create` method has two arguments: the note's title and its content.
The `list` method displays a list of notes.
The `view` method outputs the content of a note whose title is passed as an argument.
The `remove` method deletes a note whose title is passed as an argument.
1. The `create` method creates a new note in the notes.json file. The `create` method has two arguments: the note's title and its content.
2. The `list` method displays a list of notes.
3. The `view` method outputs the content of a note whose title is passed as an argument.
4. The `remove` method deletes a note whose title is passed as an argument.

To call these methods, they are specified as command-line arguments.

Expand Down Expand Up @@ -66,11 +66,6 @@ The function works, but it doesn't add data; instead, it replaces them.

So, we need to:

- прочитать уже имеющиеся данные из файла `'notes.json'` при помощи метода `fs.readFile()`
- преобразовать полученные данные в массив при помощи метода `JSON.parse()`
- дополнить массив новыми данными при помощи метода `.push()`
- преобразовать массив в JSON при помощи метода `JSON.stringify()`
- записать данные в файл `'notes.json'` при помощи метода `fs.writeFile()`
- Read the existing data from the `notes.json` file using the `fs.readFile()` method
- Convert the received data into an array using the `JSON.parse()` method
- Add new data to the array using the `.push()` method
Expand All @@ -95,7 +90,7 @@ function create(title, content) {

Run the file with the command:

```powershell
```bash
node index create title content
```

Expand Down
3 changes: 2 additions & 1 deletion stage1/modules/node-materials/node/projects/timer.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

[HOME](../../README.md)

Directly creating objects based on the `EventEmitter` class is extremely rare.
Directly creating objects based on the `EventEmitter` class is extremely rare.
More often, the interface for working with events is added to other objects. This is done through inheritance.

Let's create a class called `Timer` that will inherit from `EventEmitter`, and, as a result, its instances will have the `emit()` and `on()` methods:

```js
Expand Down
3 changes: 0 additions & 3 deletions stage1/modules/node-materials/node/stream-readable.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,6 @@ let data = "";
stream.on("data", (chunk) => (data += chunk));
```

Так как мы имеем дело с потоком данных, нам нужно знать когда поток завершится. Для этого у стрима есть событие `'end'`. Это событие срабатывает когда все данные уже переданы.
При наступлении события `'end'` выведем в консоль сообщение и длину полученных данных:

Since we are dealing with a data stream, we need to know when the stream will end. For this, the stream has an `end` event. This event is triggered when all the data has already been passed.

When the `end` event occurs, we'll output a message to the console and the length of the received data:
Expand Down
Loading

0 comments on commit 0f50dec

Please sign in to comment.