diff --git a/src/cli/args.js b/src/cli/args.js index 9e3622f791..adbef12e02 100644 --- a/src/cli/args.js +++ b/src/cli/args.js @@ -1,5 +1,15 @@ const parseArgs = () => { - // Write your code here + const args = process.argv.slice(2); + + const result = []; + + for (let i = 0; i < args.length; i += 2) { + const key = args[i].replace(/^--/, ''); + const value = args[i + 1]; + result.push(`${key} is ${value}`); + } + + console.log(result.join(', ')); }; parseArgs(); diff --git a/src/cli/env.js b/src/cli/env.js index e3616dc8e7..71ad5f5147 100644 --- a/src/cli/env.js +++ b/src/cli/env.js @@ -1,5 +1,12 @@ const parseEnv = () => { - // Write your code here + + const env = process.env; + + const rssVars = Object.entries(env) + .filter(([key]) => key.startsWith('RSS_')) + .map(([key, value]) => `${key}=${value}`); + + console.log(rssVars.join('; ')); }; parseEnv(); diff --git a/src/cp/cp.js b/src/cp/cp.js index 72c6addc9c..d4ae024c8c 100644 --- a/src/cp/cp.js +++ b/src/cp/cp.js @@ -1,6 +1,32 @@ +import { spawn } from 'node:child_process'; +import { stdin, stdout } from 'node:process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + const spawnChildProcess = async (args) => { - // Write your code here + return new Promise((resolve, reject) => { + const scriptPath = path.join(__dirname, 'files', 'script.js'); + + const child = spawn('node', [scriptPath, ...args], { + stdio: ['pipe', 'pipe', 'inherit'], + }); + + stdin.pipe(child.stdin); + + child.stdout.pipe(stdout); + + child.on('close', (code) => { + resolve(`Child process exited with code ${code}`); + }); + + child.on('error', (err) => { + reject(err); + }); + }); }; -// Put your arguments in function call to test this functionality -spawnChildProcess( /* [someArgument1, someArgument2, ...] */); +// Пример вызова для теста +spawnChildProcess(['arg1', 'arg2']); diff --git a/src/fs/copy.js b/src/fs/copy.js index e226075b4c..96b3a3d33b 100644 --- a/src/fs/copy.js +++ b/src/fs/copy.js @@ -1,5 +1,38 @@ +import fs from 'fs/promises'; +import path from 'path'; + const copy = async () => { - // Write your code here + const srcFolder = path.join('src', 'fs', 'files'); + const destFolder = path.join('src', 'fs', 'files_copy'); + + try { + await fs.access(srcFolder); + + try { + await fs.access(destFolder); + throw new Error('FS operation failed'); + } catch { + + } + + await fs.mkdir(destFolder); + + // Читаем список файлов в исходной папке + const items = await fs.readdir(srcFolder, { withFileTypes: true }); + + for (const item of items) { + if (item.isFile()) { // копируем только файлы + const srcPath = path.join(srcFolder, item.name); + const destPath = path.join(destFolder, item.name); + await fs.copyFile(srcPath, destPath); + } + } + + console.log('Папка скопирована'); + + } catch { + throw new Error('FS operation failed'); + } }; await copy(); diff --git a/src/fs/create.js b/src/fs/create.js index 6ede285599..5fda680b32 100644 --- a/src/fs/create.js +++ b/src/fs/create.js @@ -1,5 +1,16 @@ +import fs from 'fs/promises'; +import path from 'path'; + const create = async () => { - // Write your code here + const filePath = path.join('src', 'fs', 'files', 'fresh.txt'); + const content = 'I am fresh and young'; + + try { + await fs.writeFile(filePath, content, { flag: 'wx' }); + console.log('fresh.txt создан'); + } catch { + throw new Error('FS operation failed'); + } }; -await create(); +await create(); \ No newline at end of file diff --git a/src/fs/delete.js b/src/fs/delete.js index a70b13766c..84fbfac542 100644 --- a/src/fs/delete.js +++ b/src/fs/delete.js @@ -1,5 +1,18 @@ +import fs from 'fs/promises'; +import path from 'path'; + const remove = async () => { - // Write your code here + const filePath = path.join('src', 'fs', 'files', 'fileToRemove.txt'); + + try { + await fs.access(filePath); + + await fs.unlink(filePath); + + console.log('fileToRemove.txt удалён'); + } catch { + throw new Error('FS operation failed'); + } }; await remove(); diff --git a/src/fs/files/fileToRemove.txt b/src/fs/files/fileToRemove.txt deleted file mode 100644 index 43e64cd45c..0000000000 --- a/src/fs/files/fileToRemove.txt +++ /dev/null @@ -1 +0,0 @@ -How dare you! \ No newline at end of file diff --git a/src/fs/files/fresh.txt b/src/fs/files/fresh.txt new file mode 100644 index 0000000000..205d704cb7 --- /dev/null +++ b/src/fs/files/fresh.txt @@ -0,0 +1 @@ +I am fresh and young \ No newline at end of file diff --git a/src/fs/files/wrongFilename.txt b/src/fs/files/properFilename.md similarity index 100% rename from src/fs/files/wrongFilename.txt rename to src/fs/files/properFilename.md diff --git a/src/fs/files_copy/dontLookAtMe.txt b/src/fs/files_copy/dontLookAtMe.txt new file mode 100644 index 0000000000..8979bab743 --- /dev/null +++ b/src/fs/files_copy/dontLookAtMe.txt @@ -0,0 +1 @@ +What are you looking at?! \ No newline at end of file diff --git a/src/fs/files_copy/fileToRead.txt b/src/fs/files_copy/fileToRead.txt new file mode 100644 index 0000000000..5d66c332d6 --- /dev/null +++ b/src/fs/files_copy/fileToRead.txt @@ -0,0 +1,7 @@ +My content +should +be +printed +into +console +! \ No newline at end of file diff --git a/src/fs/files_copy/fresh.txt b/src/fs/files_copy/fresh.txt new file mode 100644 index 0000000000..205d704cb7 --- /dev/null +++ b/src/fs/files_copy/fresh.txt @@ -0,0 +1 @@ +I am fresh and young \ No newline at end of file diff --git a/src/fs/files_copy/hello.txt b/src/fs/files_copy/hello.txt new file mode 100644 index 0000000000..4e65f7775f --- /dev/null +++ b/src/fs/files_copy/hello.txt @@ -0,0 +1 @@ +Hello Node.js \ No newline at end of file diff --git a/src/fs/files_copy/properFilename.md b/src/fs/files_copy/properFilename.md new file mode 100644 index 0000000000..38cca5db19 --- /dev/null +++ b/src/fs/files_copy/properFilename.md @@ -0,0 +1,3 @@ +# This is a file with a wrong filename + +Hello from **markdown**! \ No newline at end of file diff --git a/src/fs/list.js b/src/fs/list.js index 0c0fa21f7e..2b4432368f 100644 --- a/src/fs/list.js +++ b/src/fs/list.js @@ -1,5 +1,18 @@ +import fs from 'fs/promises'; +import path from 'path'; + const list = async () => { - // Write your code here + const folderPath = path.join('src', 'fs', 'files'); + + try { + await fs.access(folderPath); + + const files = await fs.readdir(folderPath); + + console.log(files); + } catch { + throw new Error('FS operation failed'); + } }; await list(); diff --git a/src/fs/read.js b/src/fs/read.js index e3938be563..ebcae398fe 100644 --- a/src/fs/read.js +++ b/src/fs/read.js @@ -1,5 +1,18 @@ +import fs from 'fs/promises'; +import path from 'path'; + const read = async () => { - // Write your code here + const filePath = path.join('src', 'fs', 'files', 'fileToRead.txt'); + + try { + await fs.access(filePath); + + const content = await fs.readFile(filePath, 'utf8'); + + console.log(content); + } catch { + throw new Error('FS operation failed'); + } }; await read(); diff --git a/src/fs/rename.js b/src/fs/rename.js index b1d65b0c86..19a12e1c46 100644 --- a/src/fs/rename.js +++ b/src/fs/rename.js @@ -1,5 +1,29 @@ +import fs from 'fs/promises'; +import path from 'path'; + const rename = async () => { - // Write your code here + const folder = path.join('src', 'fs', 'files'); + const oldName = 'wrongFilename.txt'; + const newName = 'properFilename.md'; + + const oldPath = path.join(folder, oldName); + const newPath = path.join(folder, newName); + + try { + await fs.access(oldPath); + + try { + await fs.access(newPath); + throw new Error('FS operation failed'); + } catch { + + } + + await fs.rename(oldPath, newPath); + console.log(`${oldName} переименован в ${newName}`); + } catch { + throw new Error('FS operation failed'); + } }; await rename(); diff --git a/src/hash/calcHash.js b/src/hash/calcHash.js index e37c17ed62..ca121fa6c9 100644 --- a/src/hash/calcHash.js +++ b/src/hash/calcHash.js @@ -1,5 +1,25 @@ +import fs from 'fs'; +import path from 'path'; +import crypto from 'crypto'; +import { pipeline } from 'stream/promises'; + const calculateHash = async () => { - // Write your code here + try { + const filePath = path.join('src', 'hash', 'files', 'fileToCalculateHashFor.txt'); + + await fs.promises.access(filePath); + + const hash = crypto.createHash('sha256'); + const fileStream = fs.createReadStream(filePath); + + await pipeline(fileStream, hash); + + const hexHash = hash.digest('hex'); + console.log(hexHash); + + } catch { + throw new Error('FS operation failed'); + } }; await calculateHash(); diff --git a/src/modules/cjsToEsm.cjs b/src/modules/esm.mjs similarity index 50% rename from src/modules/cjsToEsm.cjs rename to src/modules/esm.mjs index 089bd2db13..64ddee2797 100644 --- a/src/modules/cjsToEsm.cjs +++ b/src/modules/esm.mjs @@ -1,17 +1,25 @@ -const path = require('node:path'); -const { release, version } = require('node:os'); -const { createServer: createServerHttp } = require('node:http'); - +import path from 'node:path'; +import { release, version } from 'node:os'; +import { createServer as createServerHttp } from 'node:http'; +import { fileURLToPath } from 'node:url'; +import { dirname } from 'node:path'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); require('./files/c.cjs'); +const aJson = require('./files/a.json'); +const bJson = require('./files/b.json'); const random = Math.random(); - -const unknownObject = random > 0.5 ? require('./files/a.json') : require('./files/b.json'); +const unknownObject = random > 0.5 ? aJson : bJson; console.log(`Release ${release()}`); console.log(`Version ${version()}`); console.log(`Path segment separator is "${path.sep}"`); +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}`); @@ -20,7 +28,6 @@ const myServer = createServerHttp((_, res) => { }); const PORT = 3000; - console.log(unknownObject); myServer.listen(PORT, () => { @@ -28,7 +35,4 @@ myServer.listen(PORT, () => { console.log('To terminate it, use Ctrl+C combination'); }); -module.exports = { - unknownObject, - myServer, -}; +export { unknownObject, myServer }; diff --git a/src/streams/read.js b/src/streams/read.js index e3938be563..9757b28044 100644 --- a/src/streams/read.js +++ b/src/streams/read.js @@ -1,5 +1,20 @@ +import fs from 'fs'; +import path from 'path'; +import { pipeline } from 'stream/promises'; + const read = async () => { - // Write your code here + try { + const filePath = path.join('src', 'streams', 'files', 'fileToRead.txt'); + + await fs.promises.access(filePath); + + const fileStream = fs.createReadStream(filePath, { encoding: 'utf-8' }); + + await pipeline(fileStream, process.stdout); + + } catch { + throw new Error('FS operation failed'); + } }; await read(); diff --git a/src/streams/transform.js b/src/streams/transform.js index 9e6c15fe84..872adb9f56 100644 --- a/src/streams/transform.js +++ b/src/streams/transform.js @@ -1,5 +1,20 @@ +import { Transform } from 'node: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 new Promise((resolve, reject) => { + reverseStream.on('end', resolve); + reverseStream.on('error', () => reject(new Error('FS operation failed'))); + process.stdin.on('error', () => reject(new Error('FS operation failed'))); + }); }; await transform(); diff --git a/src/streams/write.js b/src/streams/write.js index 84aa11e7cb..5f31206609 100644 --- a/src/streams/write.js +++ b/src/streams/write.js @@ -1,5 +1,22 @@ +import fs from 'fs'; +import path from 'path'; + const write = async () => { - // Write your code here + const filePath = path.join('src', 'streams', 'files', 'fileToWrite.txt'); + + try { + const writeStream = fs.createWriteStream(filePath, { encoding: 'utf8' }); + + process.stdin.pipe(writeStream); + + await new Promise((resolve, reject) => { + writeStream.on('finish', resolve); + writeStream.on('error', () => reject(new Error('FS operation failed'))); + process.stdin.on('error', () => reject(new Error('FS operation failed'))); + }); + } catch { + throw new Error('FS operation failed'); + } }; await write(); diff --git a/src/wt/main.js b/src/wt/main.js index e2ef054d41..9ba28c4a64 100644 --- a/src/wt/main.js +++ b/src/wt/main.js @@ -1,5 +1,25 @@ +import { Worker } from 'node:worker_threads'; +import os from 'node:os'; +import path from 'node:path'; + const performCalculations = async () => { - // Write your code here + const numCores = os.cpus().length; + const workers = []; + const results = []; + + for (let i = 0; i < numCores; i++) { + const worker = new Worker(path.resolve('src', 'wt', 'worker.js')); + workers.push(worker); + + results.push(new Promise((resolve) => { + worker.on('message', resolve); + worker.on('error', () => resolve({ status: 'error', data: null })); + worker.postMessage(10 + i); + })); + } + + const finalResults = await Promise.all(results); + console.log(finalResults); }; await performCalculations(); diff --git a/src/wt/worker.js b/src/wt/worker.js index 405595394d..0ebb40a699 100644 --- a/src/wt/worker.js +++ b/src/wt/worker.js @@ -1,8 +1,12 @@ -// n should be received from main thread -const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2); +import { parentPort, workerData } from 'node:worker_threads'; -const sendResult = () => { - // This function sends result of nthFibonacci computations to main thread -}; +const nthFibonacci = (n) => (n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2)); -sendResult(); +parentPort.on('message', (n) => { + try { + const result = nthFibonacci(n); + parentPort.postMessage({ status: 'resolved', data: result }); + } catch (err) { + parentPort.postMessage({ status: 'error', data: null }); + } +}); diff --git a/src/zip/compress.js b/src/zip/compress.js index d55209587e..ce440c3497 100644 --- a/src/zip/compress.js +++ b/src/zip/compress.js @@ -1,5 +1,26 @@ +import fs from 'node:fs'; +import zlib from 'node:zlib'; +import path from 'node:path'; + const compress = async () => { - // Write your code here + const inputPath = path.join('src', 'zip', 'files', 'fileToCompress.txt'); + const outputPath = path.join('src', 'zip', 'files', 'archive.gz'); + + try { + const gzip = zlib.createGzip(); + const source = fs.createReadStream(inputPath); + const destination = fs.createWriteStream(outputPath); + + await new Promise((resolve, reject) => { + source.pipe(gzip).pipe(destination) + .on('finish', resolve) + .on('error', () => reject(new Error('FS operation failed'))); + }); + + console.log('File compressed successfully'); + } catch (err) { + throw new Error('FS operation failed'); + } }; await compress(); diff --git a/src/zip/decompress.js b/src/zip/decompress.js index 8aaf26c8a4..d9c7dbcb29 100644 --- a/src/zip/decompress.js +++ b/src/zip/decompress.js @@ -1,5 +1,26 @@ +import fs from 'node:fs'; +import zlib from 'node:zlib'; +import path from 'node:path'; + const decompress = async () => { - // Write your code here + const inputPath = path.join('src', 'zip', 'files', 'archive.gz'); + const outputPath = path.join('src', 'zip', 'files', 'fileToCompress.txt'); + + try { + const gunzip = zlib.createGunzip(); + const source = fs.createReadStream(inputPath); + const destination = fs.createWriteStream(outputPath); + + await new Promise((resolve, reject) => { + source.pipe(gunzip).pipe(destination) + .on('finish', resolve) + .on('error', () => reject(new Error('FS operation failed'))); + }); + + console.log('File decompressed successfully'); + } catch (err) { + throw new Error('FS operation failed'); + } }; await decompress();