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: 13 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
const parseArgs = () => {
// Write your code here
// take arguments from command line excluding the first two default ones
const args = process.argv.slice(2);

const result = [];

for (let i = 0; i < args.length; i += 2) {
// remove leading '--' from argument name
const prop = args[i].replace(/^--/, '');
const value = args[i + 1];
result.push(`${prop} is ${value}`);
}

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

parseArgs();
10 changes: 9 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
const parseEnv = () => {
// Write your code here
// get all environment variables
const env = process.env;

// filter only those that start with RSS_
const rssVars = Object.entries(env)
.filter(([key]) => key.startsWith('RSS_'))
.map(([key, value]) => `${key}=${value}`);

console.log(rssVars.join('; '));
};

parseEnv();
24 changes: 22 additions & 2 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
import { spawn } from 'node:child_process';

const spawnChildProcess = async (args) => {
// Write your code here
// create child process
const child = spawn('node', ['./src/cp/files/script.js', ...args], {
stdio: ['pipe', 'pipe', process.stderr] // stdin/ stdout of child process are piped
});

// redirect stdin of main process to stdin of child process
process.stdin.pipe(child.stdin);

// redirect stdout of child process to stdout of main process
child.stdout.pipe(process.stdout);

// error handling
child.on('error', (err) => {
console.error('Child process error:', err);
});

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

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess( ['arg1', 'arg2']);
47 changes: 46 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
import fs from 'fs/promises';

const copy = async () => {
// Write your code here
const srcDir = 'src/fs/files';
const destDir = 'src/fs/files_copy';

try {
// check if source directory exists
await fs.access(srcDir);

try {
await fs.access(destDir);
// if accessible → target folder already exists
throw new Error('FS operation failed');
} catch (err) {
if (err.code !== 'ENOENT') throw err; // rethrow if error is not 'not exists'
}

// create destination directory
await fs.mkdir(destDir);

// read items in source directory
const items = await fs.readdir(srcDir, { withFileTypes: true });

// copy each item
for (const item of items) {
const srcPath = `${srcDir}/${item.name}`;
const destPath = `${destDir}/${item.name}`;

if (item.isFile()) {
await fs.copyFile(srcPath, destPath);
} else if (item.isDirectory()) {
// if has nested directory, create it and copy its files
await fs.mkdir(destPath);
const nestedItems = await fs.readdir(srcPath, { withFileTypes: true });
for (const nestedItem of nestedItems) {
const nestedSrc = `${srcPath}/${nestedItem.name}`;
const nestedDest = `${destPath}/${nestedItem.name}`;
if (nestedItem.isFile()) await fs.copyFile(nestedSrc, nestedDest);
}
}
}

console.log('Folder copied successfully!');
} catch {
throw new Error('FS operation failed');
}
};

await copy();
24 changes: 23 additions & 1 deletion src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import fs from 'fs/promises';

const create = async () => {
// Write your code here
const dirPath = `src/fs/files`;
const filePath = `${dirPath}/fresh.txt`;

// 1️⃣ Убедимся, что папка существует
await fs.mkdir(dirPath, { recursive: true });

try {
// 2️⃣ Проверяем, существует ли файл
await fs.access(filePath);
// Если доступен → файл уже есть
throw new Error('FS operation failed');
} catch (err) {
if (err.code === 'ENOENT') {
// Файла нет → создаём
await fs.writeFile(filePath, 'I am fresh and young');
console.log('File created successfully');
} else {
// Любая другая ошибка → выбрасываем
throw new Error('FS operation failed');
}
}
};

await create();
11 changes: 10 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import fs from 'fs/promises';

const remove = async () => {
// Write your code here
const filePath = 'src/fs/files/fileToRemove.txt';

try {
await fs.rm(filePath, { force: false });
console.log('File deleted successfully!');
} catch {
throw new Error('FS operation failed');
}
};

await remove();
12 changes: 11 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import fs from 'fs/promises';

const list = async () => {
// Write your code here
const dirPath = 'src/fs/files';

try {
await fs.access(dirPath);
const files = await fs.readdir(dirPath);
console.log(files);
} catch {
throw new Error('FS operation failed');
}
};

await list();
13 changes: 12 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import fs from 'fs/promises';

const read = async () => {
// Write your code here
const filePath = 'src/fs/files/fileToRead.txt';

try {
await fs.access(filePath);
const content = await fs.readFile(filePath, 'utf-8');

console.log(content);
} catch {
throw new Error('FS operation failed');
}
};

await read();
20 changes: 19 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import fs from 'fs/promises';

const rename = async () => {
// Write your code here
const dirPath = `src/fs/files`;
const srcFile = `${dirPath}/wrongFilename.txt`;
const destFile = `${dirPath}/properFilename.md`;

try {
await fs.access(srcFile);
try {
await fs.access(destFile);
throw new Error('FS operation failed'); // destination file exists
} catch (err) {
if (err.code !== 'ENOENT') throw new Error('FS operation failed');
}
await fs.rename(srcFile, destFile);
console.log('File renamed successfully!');
} catch {
throw new Error('FS operation failed');
}
};

await rename();
27 changes: 26 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
import fs from 'fs';
import crypto from 'crypto';

const calculateHash = async () => {
// Write your code here
const filePath = 'src/hash/files/fileToCalculateHashFor.txt';

try {
// create read stream
const stream = fs.createReadStream(filePath);

// create hash object
const hash = crypto.createHash('sha256');

// stream piping
stream.on('data', chunk => hash.update(chunk));

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

stream.on('error', () => {
throw new Error('FS operation failed');
});
} catch {
throw new Error('FS operation failed');
}
};

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

This file was deleted.

38 changes: 38 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { release, version } from 'node:os';
import { createServer as createServerHttp } from 'node:http';

import './files/c.cjs';

const random = Math.random();

import aJson from './files/a.json' with { type: 'json' };
import bJson from './files/b.json' with { type: 'json' };

const unknownObject = random > 0.5 ? aJson : bJson;

console.log(`Release ${release()}`);
console.log(`Version ${version()}`);
console.log(`Path segment separator is "${dirname('/')}"`);

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

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 };
15 changes: 14 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import fs from 'fs';

const read = async () => {
// Write your code here
const filePath = 'src/streams/files/fileToRead.txt';

try {
const stream = fs.createReadStream(filePath, 'utf-8');
stream.pipe(process.stdout);

stream.on('error', () => {
throw new Error('FS operation failed');
});
} catch {
throw new Error('FS operation failed');
}
};

await read();
11 changes: 10 additions & 1 deletion src/streams/transform.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { Transform } from 'stream';

const transform = async () => {
// Write your code here
const reverseStream = new Transform({
transform(chunk, encoding, callback) {
const reversed = chunk.toString().split('').reverse().join('');
callback(null, reversed);
}
});

process.stdin.pipe(reverseStream).pipe(process.stdout);
};

await transform();
15 changes: 14 additions & 1 deletion src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import fs from 'fs';

const write = async () => {
// Write your code here
const filePath = 'src/streams/files/fileToWrite.txt';

try {
const writableStream = fs.createWriteStream(filePath);
process.stdin.pipe(writableStream);

writableStream.on('error', () => {
throw new Error('FS operation failed');
});
} catch {
throw new Error('FS operation failed');
}
};

await write();
Loading