diff --git a/src/cli/args.js b/src/cli/args.js index 9e3622f791..44c623ca67 100644 --- a/src/cli/args.js +++ b/src/cli/args.js @@ -1,5 +1,18 @@ -const parseArgs = () => { - // Write your code here -}; - -parseArgs(); +const parseArgs = () => { + let arg = process.argv; + const getArg = arg.reduce((acc, current, index) => { + if (current.startsWith("--")) { + const val = current.substring(2); + const next = arg[index + 1]; + if (next) { + const formattedPair = `${val} is ${next}`; + return acc + (acc.length ? ", " : "") + formattedPair; + } + } + return acc; + }, ""); + + console.log(getArg); +}; + +parseArgs(); diff --git a/src/cli/env.js b/src/cli/env.js index e3616dc8e7..66ddde21c8 100644 --- a/src/cli/env.js +++ b/src/cli/env.js @@ -1,5 +1,13 @@ -const parseEnv = () => { - // Write your code here -}; - -parseEnv(); +const parseEnv = () => { + let env = process.env; + let selectRss = Object.entries(env) + .filter(([key]) => key.startsWith("RSS_")) + .map(([key, value], index) => { + return `${key}=${value}`; + }); + let result = selectRss.join("; "); + + console.log(result); +}; + +parseEnv(); diff --git a/src/cp/cp.js b/src/cp/cp.js index 72c6addc9c..fe5277b336 100644 --- a/src/cp/cp.js +++ b/src/cp/cp.js @@ -1,6 +1,6 @@ -const spawnChildProcess = async (args) => { - // Write your code here -}; - -// Put your arguments in function call to test this functionality -spawnChildProcess( /* [someArgument1, someArgument2, ...] */); +const spawnChildProcess = async (args) => { + // Write your code here +}; + +// Put your arguments in function call to test this functionality +spawnChildProcess( /* [someArgument1, someArgument2, ...] */); diff --git a/src/cp/files/script.js b/src/cp/files/script.js index 0c6654f12f..c37d6efdc2 100644 --- a/src/cp/files/script.js +++ b/src/cp/files/script.js @@ -1,19 +1,19 @@ -import { EOL } from 'node:os'; -import { argv, stdout, stdin, exit } from 'node:process'; - -const args = argv.slice(2); - -console.log(`Total number of arguments is ${args.length}`); -console.log(`Arguments: ${JSON.stringify(args)}${EOL}`); - -const echoInput = (chunk) => { - const chunkStringified = chunk.toString(); - - if (chunkStringified.includes('CLOSE')) { - exit(0); - } - - stdout.write(`Received from master process: ${chunk.toString()}${EOL}`); -}; - -stdin.on('data', echoInput); +import { EOL } from 'node:os'; +import { argv, stdout, stdin, exit } from 'node:process'; + +const args = argv.slice(2); + +console.log(`Total number of arguments is ${args.length}`); +console.log(`Arguments: ${JSON.stringify(args)}${EOL}`); + +const echoInput = (chunk) => { + const chunkStringified = chunk.toString(); + + if (chunkStringified.includes('CLOSE')) { + exit(0); + } + + stdout.write(`Received from master process: ${chunk.toString()}${EOL}`); +}; + +stdin.on('data', echoInput); diff --git a/src/fs/copy.js b/src/fs/copy.js index e226075b4c..a6475d4353 100644 --- a/src/fs/copy.js +++ b/src/fs/copy.js @@ -1,5 +1,34 @@ -const copy = async () => { - // Write your code here -}; - -await copy(); +import fs from "fs/promises"; +import path from "path"; + +const copy = async () => { + let folderFiles = path.join(import.meta.dirname, "files"); + let folderFilesCopy = path.join(import.meta.dirname, "files_copy"); + let errorText = "FS operation failed"; + + try { + //create promise to check if folders exist + let results = await Promise.allSettled([ + fs.access(folderFiles, fs.constants.F_OK), + fs.access(folderFilesCopy, fs.constants.F_OK), + ]); + //save exist check results + let isFolderFiles = results[0].status === "fulfilled"; + let isfolderFilesCopy = results[1].status === "rejected"; + + //copy to new folder if conditions true + if (isFolderFiles && isfolderFilesCopy) { + try { + await fs.cp(folderFiles, folderFilesCopy, { recursive: true }); + } catch (err) { + throw new Error(errorText); + } + } else { + throw new Error(errorText); + } + } catch (error) { + throw new Error(errorText); + } +}; + +await copy(); diff --git a/src/fs/create.js b/src/fs/create.js index 6ede285599..9260641815 100644 --- a/src/fs/create.js +++ b/src/fs/create.js @@ -1,5 +1,16 @@ -const create = async () => { - // Write your code here -}; - -await create(); +import fs from "fs/promises"; +import path from "path"; + +const create = async () => { + let pathFolder = path.join(import.meta.dirname, "files", "fresh.txt"); + let fileText = "I am fresh and young"; + let errorText = "FS operation failed"; + + try { + await fs.writeFile(pathFolder, fileText, { flag: "wx" }); + } catch (error) { + throw new Error(errorText); + } +}; + +await create(); diff --git a/src/fs/delete.js b/src/fs/delete.js index a70b13766c..76857a4102 100644 --- a/src/fs/delete.js +++ b/src/fs/delete.js @@ -1,5 +1,15 @@ -const remove = async () => { - // Write your code here -}; - -await remove(); +import fs from "fs/promises"; +import path from "path"; + +const remove = async () => { + let removeFile = path.join(import.meta.dirname, "files", "fileToRemove.txt"); + let errorText = "FS operation failed"; + + try { + await fs.rm(removeFile); + } catch (error) { + throw new Error(errorText); + } +}; + +await remove(); diff --git a/src/fs/files/fileToRead.txt b/src/fs/files/fileToRead.txt index 5d66c332d6..57171e25ab 100644 --- a/src/fs/files/fileToRead.txt +++ b/src/fs/files/fileToRead.txt @@ -1,7 +1,7 @@ -My content -should -be -printed -into -console +My content +should +be +printed +into +console ! \ No newline at end of file diff --git a/src/fs/files/wrongFilename.txt b/src/fs/files/wrongFilename.txt index 38cca5db19..926e341f91 100644 --- a/src/fs/files/wrongFilename.txt +++ b/src/fs/files/wrongFilename.txt @@ -1,3 +1,3 @@ -# This is a file with a wrong filename - +# 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..fcd52bc47f 100644 --- a/src/fs/list.js +++ b/src/fs/list.js @@ -1,5 +1,16 @@ -const list = async () => { - // Write your code here -}; - -await list(); +import fs from "fs/promises"; +import path from "path"; + +const list = async () => { + let folderPath = path.join(import.meta.dirname, "files"); + let errorText = "FS operation failed"; + + try { + let data = await fs.readdir(folderPath); + console.log(data); + } catch (error) { + throw new Error(errorText); + } +}; + +await list(); diff --git a/src/fs/read.js b/src/fs/read.js index e3938be563..16f05f94b4 100644 --- a/src/fs/read.js +++ b/src/fs/read.js @@ -1,5 +1,16 @@ -const read = async () => { - // Write your code here -}; - -await read(); +import fs from "fs/promises"; +import path from "path"; + +const read = async () => { + let filePath = path.join(import.meta.dirname, "files", "fileToRead.txt"); + let errorText = "FS operation failed"; + + try { + let data = await fs.readFile(filePath, "utf8"); + console.log(data); + } catch (error) { + throw new Error(errorText); + } +}; + +await read(); diff --git a/src/fs/rename.js b/src/fs/rename.js index b1d65b0c86..7787308412 100644 --- a/src/fs/rename.js +++ b/src/fs/rename.js @@ -1,5 +1,31 @@ -const rename = async () => { - // Write your code here -}; - -await rename(); +import fs from "fs/promises"; +import path from "path"; + +const rename = async () => { + let oldFile = path.join(import.meta.dirname, "files", "wrongFilename.txt"); + let newFile = path.join(import.meta.dirname, "files", "properFilename.md"); + let errorText = "FS operation failed"; + + try { + let results = await Promise.allSettled([ + fs.access(oldFile, fs.constants.F_OK), + fs.access(newFile, fs.constants.F_OK), + ]); + let isOldFiles = results[0].status === "fulfilled"; + let isNewFiles = results[1].status === "rejected"; + + if (isOldFiles && isNewFiles) { + try { + await fs.rename(oldFile, newFile); + } catch (err) { + throw new Error(errorText); + } + } else { + throw new Error(errorText); + } + } catch (error) { + throw new Error(errorText); + } +}; + +await rename(); diff --git a/src/hash/calcHash.js b/src/hash/calcHash.js index e37c17ed62..460cb24d88 100644 --- a/src/hash/calcHash.js +++ b/src/hash/calcHash.js @@ -1,5 +1,26 @@ -const calculateHash = async () => { - // Write your code here -}; - -await calculateHash(); +import { createHash } from "crypto"; +import { createReadStream } from "fs"; +import { pipeline } from "stream/promises"; +import path from "path"; + +const calculateHash = async () => { + const hashFile = path.join( + import.meta.dirname, + "files", + "fileToCalculateHashFor.txt" + ); + + const hash = createHash("sha256"); + const stream = createReadStream(hashFile); + + try { + await pipeline(stream, hash); + const hexHash = hash.digest("hex"); + console.log(hexHash); + return hexHash; + } catch (error) { + throw new Error(error); + } +}; + +await calculateHash(); diff --git a/src/modules/esm.mjs b/src/modules/esm.mjs new file mode 100644 index 0000000000..c1788b4079 --- /dev/null +++ b/src/modules/esm.mjs @@ -0,0 +1,45 @@ +import path from "path"; +import { release, version } from "os"; +import { createServer as createServerHttp } from "http"; +import "./files/c.cjs"; + +const random = Math.random(); +let unknownObject; +if (random > 0.5) { + unknownObject = ( + await import("./files/a.json", { + with: { type: "json" }, + }) + ).default; +} else { + unknownObject = ( + await import("./files/b.json", { + with: { type: "json" }, + }) + ).default; +} + +console.log(`Release ${release()}`); +console.log(`Version ${version()}`); +console.log(`Path segment separator is "${path.sep}"`); + +console.log(`Path to current file is ${import.meta.filename}`); +console.log(`Path to current directory is ${import.meta.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 default { + unknownObject, + myServer, +}; diff --git a/src/modules/files/a.json b/src/modules/files/a.json index d1f6dac48a..e4ff5e3611 100644 --- a/src/modules/files/a.json +++ b/src/modules/files/a.json @@ -1,5 +1,5 @@ -{ - "a": 1, - "b": 2, - "c": 3 -} +{ + "a": 1, + "b": 2, + "c": 3 +} diff --git a/src/modules/files/b.json b/src/modules/files/b.json index e442128649..b8f017c661 100644 --- a/src/modules/files/b.json +++ b/src/modules/files/b.json @@ -1,5 +1,5 @@ -{ - "a": 11, - "b": 22, - "c": 33 -} +{ + "a": 11, + "b": 22, + "c": 33 +} diff --git a/src/modules/files/c.cjs b/src/modules/files/c.cjs index df728e1627..cf8474a352 100644 --- a/src/modules/files/c.cjs +++ b/src/modules/files/c.cjs @@ -1 +1 @@ -console.log('Hello from c.cjs!'); +console.log('Hello from c.cjs!'); diff --git a/src/streams/files/fileToWrite.txt b/src/streams/files/fileToWrite.txt index e69de29bb2..d3f5a12faa 100644 --- a/src/streams/files/fileToWrite.txt +++ b/src/streams/files/fileToWrite.txt @@ -0,0 +1 @@ + diff --git a/src/streams/read.js b/src/streams/read.js index e3938be563..306a17483c 100644 --- a/src/streams/read.js +++ b/src/streams/read.js @@ -1,5 +1,16 @@ -const read = async () => { - // Write your code here -}; - -await read(); +import { createReadStream } from "fs"; +import { pipeline } from "stream/promises"; +import path from "path"; + +const read = async () => { + const readFile = path.join(import.meta.dirname, "files", "fileToRead.txt"); + const streamRead = createReadStream(readFile, { encoding: "utf-8" }); + + try { + await pipeline(streamRead, process.stdout); + } catch (error) { + throw new Error(error); + } +}; + +await read(); diff --git a/src/streams/transform.js b/src/streams/transform.js index 9e6c15fe84..751bf8a7d4 100644 --- a/src/streams/transform.js +++ b/src/streams/transform.js @@ -1,5 +1,19 @@ -const transform = async () => { - // Write your code here -}; - -await transform(); +import { Transform } from "stream"; +import { pipeline } from "stream/promises"; + +const transform = async () => { + class reverseTranform extends Transform { + _transform(chunk, _, callback) { + const data = chunk?.toString().split("").reverse().join(""); + callback(null, data); + } + } + + try { + await pipeline(process.stdin, new reverseTranform(), process.stdout); + } catch (error) { + console.error(error); + } +}; + +await transform(); diff --git a/src/streams/write.js b/src/streams/write.js index 84aa11e7cb..7f5b8b9756 100644 --- a/src/streams/write.js +++ b/src/streams/write.js @@ -1,5 +1,16 @@ -const write = async () => { - // Write your code here -}; - -await write(); +import { createWriteStream } from "fs"; +import { pipeline } from "stream/promises"; +import path from "path"; + +const write = async () => { + const writeFile = path.join(import.meta.dirname, "files", "fileToWrite.txt"); + const writeStream = createWriteStream(writeFile); + + try { + await pipeline(process.stdin, writeStream); + } catch (error) { + throw new Error(error); + } +}; + +await write(); diff --git a/src/wt/main.js b/src/wt/main.js index e2ef054d41..a267c5a3fd 100644 --- a/src/wt/main.js +++ b/src/wt/main.js @@ -1,5 +1,40 @@ -const performCalculations = async () => { - // Write your code here -}; - -await performCalculations(); +import { Worker } from "worker_threads"; +import os from "os"; +import path from "path"; + +const performCalculations = async () => { + const cores = os.cpus().length; + const workerPath = path.join(import.meta.dirname, "worker.js"); + const workerPromises = []; + + for (let i = 0; i < cores; i++) { + const workerData = 10 + i; + + const workerPromise = new Promise((resolve, reject) => { + const worker = new Worker(workerPath); + + worker.postMessage(workerData); + + worker.on("message", (message) => { + worker.terminate(); + resolve({ status: "resolved", data: message.data }); + }); + + worker.on("error", (err) => { + worker.terminate(); + resolve({ status: "error", data: null }); + }); + }); + + workerPromises.push(workerPromise); + } + + try { + const results = await Promise.all(workerPromises); + console.log(results); + } catch (error) { + console.error(error); + } +}; + +await performCalculations(); diff --git a/src/wt/worker.js b/src/wt/worker.js index 405595394d..7f36a67e77 100644 --- a/src/wt/worker.js +++ b/src/wt/worker.js @@ -1,8 +1,17 @@ -// n should be received from main thread -const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2); - -const sendResult = () => { - // This function sends result of nthFibonacci computations to main thread -}; - -sendResult(); +import { parentPort } from "worker_threads"; + +const nthFibonacci = (n) => + n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2); + +const sendResult = async () => { + parentPort.on("message", (data) => { + try { + const result = nthFibonacci(data); + parentPort.postMessage({ status: "resolved", data: result }); + } catch (error) { + parentPort.postMessage({ status: "error", data: null }); + } + }); +}; + +sendResult(); diff --git a/src/zip/compress.js b/src/zip/compress.js index d55209587e..28bd2bf9aa 100644 --- a/src/zip/compress.js +++ b/src/zip/compress.js @@ -1,5 +1,23 @@ -const compress = async () => { - // Write your code here -}; - -await compress(); +import path from "path"; +import { createReadStream, createWriteStream } from "fs"; +import zlib from "zlib"; +import { pipeline } from "stream/promises"; + +const compress = async () => { + const readFile = path.join( + import.meta.dirname, + "files", + "fileToCompress.txt" + ); + const zipFile = path.join(import.meta.dirname, "files", "archive.gz"); + const streamRead = createReadStream(readFile); + const streamWrite = createWriteStream(zipFile); + + try { + await pipeline(streamRead, zlib.Gzip(), streamWrite); + } catch (error) { + throw new Error(error); + } +}; + +await compress(); diff --git a/src/zip/decompress.js b/src/zip/decompress.js index 8aaf26c8a4..7e283f8a70 100644 --- a/src/zip/decompress.js +++ b/src/zip/decompress.js @@ -1,5 +1,23 @@ -const decompress = async () => { - // Write your code here -}; - -await decompress(); +import path from "path"; +import { createReadStream, createWriteStream } from "fs"; +import zlib from "zlib"; +import { pipeline } from "stream/promises"; + +const decompress = async () => { + const readFile = path.join( + import.meta.dirname, + "files", + "fileToCompress.txt" + ); + const zipFile = path.join(import.meta.dirname, "files", "archive.gz"); + const streamRead = createReadStream(zipFile); + const streamWrite = createWriteStream(readFile); + + try { + await pipeline(streamRead, zlib.Unzip(), streamWrite); + } catch (error) { + throw new Error(error); + } +}; + +await decompress(); diff --git a/src/zip/files/archive.gz b/src/zip/files/archive.gz new file mode 100644 index 0000000000..b163d0003a Binary files /dev/null and b/src/zip/files/archive.gz differ