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
13 changes: 11 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
const result = [];

for (let i = 0; i < args.length; i += 2) {
const propName = args[i].slice(2); // Удалим '--'
const value = args[i + 1];
result.push(`${propName} is ${value}`);
}

console.log(result.join(', '));
};

parseArgs();
parseArgs();
9 changes: 8 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
const parseEnv = () => {
// Write your code here
const envV = process.env;
const rssV = [];
for (const key in envV) {
if (key.startsWith('RSS_')) {
rssV.push(`${key}=${envV[key]}`);
}
}
console.log(rssV.join('; '));
};

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

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

// ДЛЯ ЦЕЛЕЙ ТЕСТИРОВАНИЯ РАБОТЫ ПРИЛОЖЕНИЯ СРАЗУ ПОСЛЕ СТАРТА ВВЕСТИ ЛЮБУЮ СТРОКУ
// И НАЖАТЬ ЕНТЕР. ЧТОБЫ ВЫЙТИЁ ИЗ ПРОЦЕССА ВВЕСЬТИ CLOSE именно большими буквами

const spawnChildProcess = async (args) => {
// Write your code here
// Путь к script.js в папке files
const scriptPath = join(__dirname, 'files', 'script.js');

const childProcess = spawn('node', [scriptPath, ...args], {
stdio: ['pipe', 'pipe', 'inherit']
});

// Связываем stdin и stdout родительского и дочернего процессов
process.stdin.pipe(childProcess.stdin);
childProcess.stdout.pipe(process.stdout);

// Обработка завершения дочернего процесса
childProcess.on('exit', (code) => {
console.log(`\nChild process exited with code ${code}`);
});

return childProcess;
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
// Тестируем с аргументами
spawnChildProcess(['argument1', 'argument2', 'argument3', 'argument4']);
66 changes: 64 additions & 2 deletions src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,67 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);

const copy = async () => {
// Write your code here
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);

const copy = async () => {
const srcToFiles = path.join(_dirname, 'files');
const destFilesCopy = path.join(_dirname, 'files_copy');

try {
// Проверка существования исходной папки
await fs.access(srcToFiles);

// Проверка, существует ли уже папка назначения
try {
await fs.access(destFilesCopy);
throw new Error('FS operation failed');
} catch (error) {
// Если ошибка не связана с отсутствием папки, работаем дальше
if (error.message === 'FS operation failed') throw error;

// Создаем основную папку
await fs.mkdir(destFilesCopy);

// Рекурсия-функция для копирования
const copyItems = async (currentSrc, currentDestination) => {
const items = await fs.readdir(currentSrc);

for (const item of items) {
const srcPath = path.join(currentSrc, item);
const destPath = path.join(currentDestination, item);
const stat = await fs.stat(srcPath);

if (stat.isFile()) {
// Копируем файл
await fs.copyFile(srcPath, destPath);
} else if (stat.isDirectory()) {
// Создаем подпапку и копируем её контент
await fs.mkdir(destPath);
await copyItems(srcPath, destPath);
}
}
};

// Стартуем копирование
await copyItems(srcToFiles, destFilesCopy);
}
} catch (error) {
if (error.message !== 'FS operation failed') {
throw new Error('FS operation failed');
}
throw error;
}
}
};

await copy();
await copy();
25 changes: 23 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import { promises as fs } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const fileName = fileURLToPath(import.meta.url);
const _dirName = dirname(fileName);

const create = async () => {
// Write your code here
};
const filePath = join(_dirName, 'files', 'fresh.txt');
const content = 'I am fresh and young';

try {
await fs.access(filePath);

const errorText = 'FS operation failed';
throw new Error(errorText);
} catch (error) {
if (error.code === 'ENOENT') {
const standard = 'utf8';
await fs.writeFile(filePath, content, standard);
} else {
throw error;
}
}
};
await create();
22 changes: 20 additions & 2 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const fileName = fileURLToPath(import.meta.url);
const dirName = path.dirname(fileName);

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

try {
// Проверяем существует ли файл
await fs.access(filePath);

// Удаляем файл
await fs.unlink(filePath);
} catch (error) {
// Если файла нет или произошла к-л ошибка
throw new Error('FS operation failed');
}
};

await remove();
await remove();
File renamed without changes.
25 changes: 23 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import path from 'path';

const _fileName = fileURLToPath(import.meta.url);
const _dirName = path.dirname(_fileName);

const list = async () => {
// Write your code here
const folderPath = path.join(_dirName, 'files');

try {
// Проверяем существует ли папка
await fs.access(folderPath);

// Смотрим содержимое папки
const files = await fs.readdir(folderPath);

// Массив имен файлов в консоль
console.log(files);
} catch (error) {
// Даем ошибку
throw new Error('FS operation failed');
}
};

await list();
await list();
19 changes: 18 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const _fileName = fileURLToPath(import.meta.url);
const _dirName = path.dirname(_fileName);

const read = async () => {
// Write your code here
const fileToReadName = 'fileToRead.txt';
const filePath = path.join(_dirName, 'files', fileToReadName);

try {
await fs.access(filePath);
const standard = 'utf-8';
const content = await fs.readFile(filePath, standard);
console.log(content);
} catch (error) {
throw new Error('FS operation failed');
}
};

await read();
34 changes: 32 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

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

const rename = async () => {
// Write your code here
const wrongFilePath = path.join(__dirname, 'files', 'wrongFilename.txt');
const properFilePath = path.join(__dirname, 'files', 'wrongFileName.md');

try {
// Проверяем существование исходного файла
await fs.access(wrongFilePath);

// Проверяем, не существует ли уже целевой файл
try {
await fs.access(properFilePath);
throw new Error('FS operation failed');
} catch (error) {
// Если ошибка не связана с отсутствием файла, пробрасываем дальше
if (error.message === 'FS operation failed') throw error;

// Переименовываем файл
await fs.rename(wrongFilePath, properFilePath);
}
} catch (error) {
if (error.message !== 'FS operation failed') {
throw new Error('FS operation failed');
}
throw error;
}
};

await rename();
await rename();
31 changes: 29 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const calculateHash = async () => {
// Write your code here
const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename);
const fileNameToCalculateHashFor = 'fileToCalculateHashFor.txt';
const filePath = join(_dirname, 'files', fileNameToCalculateHashFor);

return new Promise((res, rej) => {
const hash = createHash('sha256');
const stream = createReadStream(filePath);

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

stream.on('end', () => {
const hexHash = hash.digest('hex');
console.log(hexHash);
res(hexHash);
});

stream.on('error', (error) => {
rej(error);
});
});
};

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

This file was deleted.

Loading