Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
let output = [];

for (let i = 0; i < args.length; i += 2) {
const key = args[i].startsWith("--") ? args[i].slice(2) : args[i];
const value = args[i + 1];

output.push(`${key} is ${value}`);
}

console.log(output.join(", "));
};

parseArgs();
parseArgs();
11 changes: 10 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
const ENV_NAME="RSS_";
process.env.RSS_name1 = 'value1';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this is here???
This side effect gives the wrong result of function.

process.env.RSS_name2 = 'value2';

const parseEnv = () => {
// Write your code here
const rssVariables = Object.entries(process.env)
.filter(([key, _]) => key.startsWith(ENV_NAME))
.map(([key, value]) => `${key}=${value}`)
.join('; ');

console.log(rssVariables);
};

parseEnv();
29 changes: 26 additions & 3 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DIR = "files";
const FILE_NAME = "script.js";

const spawnChildProcess = async (args) => {
// Write your code here
const scriptPath = path.join(__dirname, DIR, FILE_NAME);
const child = spawn("node", [scriptPath, ...args], {
stdio: ["pipe", "pipe", "inherit", "ipc"],
});

process.stdin.pipe(child.stdin);

child.stdout.pipe(process.stdout);

child.on("error", (error) => {
console.error(`Error in child process: ${error.message}`);
});

child.on("exit", (code) => {
console.log(`Child process exited with code ${code}`);
});
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess([1, 2, 3, 4, 5]);
34 changes: 33 additions & 1 deletion src/fs/copy.js
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,37 @@
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
import { exists } from "./vendors.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DIR = "files";

const copy = async () => {
// Write your code here
const sourceDir = path.join(__dirname, DIR);
const destDir = path.join(__dirname, "files_copy");

if (!(await exists(sourceDir)) || (await exists(destDir))) {
throw new Error("FS operation failed");
}

copyFiles(sourceDir, destDir);
};

const copyFiles = async (src, dest) => {
await fs.mkdir(dest, { recursive: true });

const entries = await fs.readdir(src, { withFileTypes: true });

for (let entry of entries) {
let srcPath = path.join(src, entry.name);
let destPath = path.join(dest, entry.name);

entry.isDirectory()
? copyDirectory(srcPath, destPath)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is copyDirectory??? Where is it?

: await fs.copyFile(srcPath, destPath);
}
};

await copy();
21 changes: 19 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import fs from "fs";
import path from "path";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import path, { dirname } from "path";

You have two imports from one module

import { fileURLToPath } from "url";
import { dirname } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const MESSAGE = "I am fresh and young";
const FILE_NAME = "fresh.txt";
const DIR = "files";

const create = async () => {
// Write your code here
const filePath = path.join(__dirname, DIR, FILE_NAME);

if (fs.existsSync(filePath)) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне кажется, здесь Вы делаете лишнюю работу, но она недостаточна...
При работе с файловой системой могут возникнуть разнообразные эксепшины, которые Вы не отлавливаете.
Вам нужно было writeFile обернуть в блок try ... catch, в метод передать флаг wx (он бы выбрасывал исключение , если файл уже существует), это исключение отлавливалось бы в кетче (наравне с любыми другими ошибками).

throw new Error("FS operation failed");
}

fs.writeFileSync(filePath, MESSAGE);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В задании рекомендовано использовать асинхронные методы. Сейчас это не важно, но в данное задание - подготовка к следующим и там синхронные уже не прокатят.

};

await create();
await create();
20 changes: 18 additions & 2 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
import { exists } from "./vendors.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const remove = async () => {
// Write your code here
const dirPath = path.join(__dirname, "files");
const filePath = path.join(dirPath, "fileToRemove.txt");

if (!(await exists(filePath))) {
throw new Error("FS operation failed");
}

await fs.unlink(filePath);
};

await remove();
await remove();
22 changes: 20 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
import { exists } from "./vendors.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const list = async () => {
// Write your code here
const dirPath = path.join(__dirname, "files");

if (!(await exists(dirPath))) {
throw new Error("FS operation failed");
}

const files = await fs.readdir(dirPath);
files.forEach((file) => {
console.log(file);
});
};

await list();
await list();
26 changes: 24 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
import { exists } from "./vendors.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const read = async () => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another version of list.js?
Something is wrong here.

// Write your code here
const dirPath = path.join(__dirname, "files");

if (!(await exists(dirPath))) {
throw new Error("FS operation failed: files folder does not exist");
}

try {
const files = await fs.readdir(dirPath);
files.forEach((file) => {
console.log(file);
});
} catch (err) {
throw new Error("Error reading files from the directory");
}
};

await read();
await read();
23 changes: 21 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
import { exists } from "./vendors.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DIR = "files";

const rename = async () => {
// Write your code here
const fileDir = path.join(__dirname, DIR);

const oldFilePath = path.join(fileDir, "wrongFilename.txt");
const newFilePath = path.join(fileDir, "properFilename.md");

if (!(await exists(oldFilePath)) || (await exists(newFilePath))) {
throw new Error("FS operation failed");
}

await fs.rename(oldFilePath, newFilePath);
};

await rename();
rename();
10 changes: 10 additions & 0 deletions src/fs/vendors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { promises as fs } from "fs";

export const exists = async (path) => {
try {
await fs.stat(path);
return true;
} catch {
return false;
}
};
28 changes: 27 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
import fs from 'fs';
import crypto from 'crypto';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const FILE_NAME = "fileToCalculateHashFor.txt";
const DIR = "files";

const calculateHash = async () => {
// Write your code here
const filePath = path.join(__dirname, DIR, FILE_NAME);
const hash = crypto.createHash('sha256');
const fileStream = fs.createReadStream(filePath);

fileStream.on('data', (data) => {
hash.update(data);
});

fileStream.on('end', () => {
const hexHash = hash.digest('hex');
console.log(`SHA256 Hash: ${hexHash}`);
});

fileStream.on('error', (err) => {
console.error(`Error reading file: ${err.message}`);
});
};

await calculateHash();
40 changes: 0 additions & 40 deletions src/modules/cjsToEsm.cjs

This file was deleted.

39 changes: 39 additions & 0 deletions src/modules/cjsToEsm.mjs
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should rename this file.

Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import path from "path";
import { fileURLToPath } from "url";
import os from "os";
import { createServer as createServerHttp } from "http";
import "./files/c.js";

const random = Math.random();
let unknownObject;

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

if (random > 0.5) {
unknownObject = await import("./files/a.json", { assert: { type: "json" } });
} else {
unknownObject = await import("./files/b.json", { assert: { type: "json" } });
}

console.log(`Release ${os.release()}`);
console.log(`Version ${os.version()}`);
console.log(`Path segment separator is "${path.sep}"`);

console.log(`Path to current file is ${__filename}`);
console.log(`Path to current directory is ${__dirname}`);

const myServer = createServerHttp((_, res) => {
res.end("Request accepted");
});

const PORT = 3000;

console.log(unknownObject);

myServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
console.log("To terminate it, use Ctrl+C combination");
});

export { unknownObject, myServer };
Binary file added src/screenshots/cli/args.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/cli/env.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/cp/cp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/fs/copy.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/fs/create.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/fs/delete.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/fs/list.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/fs/read.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/fs/rename.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/hash/calcHash.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/modules/cjsToEsm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/streams/read.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/streams/transform.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/streams/write.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/zip/compress.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/screenshots/zip/decompress.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 15 additions & 2 deletions src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const FILE_NAME = "fileToRead.txt";
const DIR = "files";

const read = async () => {
// Write your code here
const filePath = path.join(__dirname, DIR, FILE_NAME);
const readStream = fs.createReadStream(filePath);

readStream.pipe(process.stdout);
};

await read();
await read();
Loading