diff --git a/src/cli/args.js b/src/cli/args.js index 9e3622f791..935745ac51 100644 --- a/src/cli/args.js +++ b/src/cli/args.js @@ -1,5 +1,13 @@ +import { argv } from "node:process"; + const parseArgs = () => { // Write your code here + const justArguments = argv.slice(2); + const result = []; + for (let i = 0; i < justArguments.length; i += 2) { + result.push(`${justArguments[i].slice(2)} is ${justArguments[i + 1]}`); + } + console.log(result.join(", ")); }; parseArgs(); diff --git a/src/cli/env.js b/src/cli/env.js index e3616dc8e7..7d0f84dafa 100644 --- a/src/cli/env.js +++ b/src/cli/env.js @@ -1,5 +1,14 @@ const parseEnv = () => { // Write your code here + const envVariables = Object.entries(process.env); + const filteredVariables = envVariables.filter(([key]) => + key.startsWith("RSS_"), + ); + const stringifyFilteredVariables = filteredVariables.map( + ([key, value]) => `${key}=${value}`, + ); + const jointResult = stringifyFilteredVariables.join("; "); + console.log(jointResult); }; parseEnv(); diff --git a/src/cp/cp.js b/src/cp/cp.js index 72c6addc9c..7a27d9c477 100644 --- a/src/cp/cp.js +++ b/src/cp/cp.js @@ -1,6 +1,17 @@ +import { spawn } from "node:child_process"; +import { URL, fileURLToPath } from "node:url"; const spawnChildProcess = async (args) => { // Write your code here + const scriptURL = new URL("./files/script.js", import.meta.url); + const scriptPath = fileURLToPath(scriptURL); + const child = spawn("node", [scriptPath, ...args], { + stdio: ["pipe", "pipe", "inherit"], + }); + + process.stdin.pipe(child.stdin); + + child.stdout.pipe(process.stdout); }; // Put your arguments in function call to test this functionality -spawnChildProcess( /* [someArgument1, someArgument2, ...] */); +spawnChildProcess(["someArgument1", "someArgument2", "other argument"]); diff --git a/src/fs/copy.js b/src/fs/copy.js index e226075b4c..129ef1a134 100644 --- a/src/fs/copy.js +++ b/src/fs/copy.js @@ -1,5 +1,29 @@ +import { cp } from "node:fs/promises"; +import { URL, fileURLToPath } from "node:url"; const copy = async () => { // Write your code here + const srcURL = new URL("./files/", import.meta.url); + const src = fileURLToPath(srcURL); + const destURL = new URL("./files_copy", import.meta.url); + const dest = fileURLToPath(destURL); + const errorMessage = "FS operation failed"; + try { + try { + await cp(src, dest, { + errorOnExist: true, + recursive: true, + force: false, + }); + } catch (e) { + throw new Error(errorMessage); + } + } catch (e) { + if (e instanceof Error && e.message === errorMessage) { + console.log(e.message); + } else { + console.log(e); + } + } }; await copy(); diff --git a/src/fs/create.js b/src/fs/create.js index 6ede285599..a22c8fea84 100644 --- a/src/fs/create.js +++ b/src/fs/create.js @@ -1,5 +1,26 @@ +import { writeFile, access } from "node:fs/promises"; +import { URL, fileURLToPath } from "node:url"; + const create = async () => { // Write your code here + const content = "I am fresh and young"; + const fileURL = new URL("./files/fresh.txt", import.meta.url); + const file = fileURLToPath(fileURL); + const errorMessage = "FS operation failed"; + try { + await access(file); + throw new Error(errorMessage); + } catch (e) { + if (e instanceof Error && e.message === errorMessage) { + console.log(e.message); + } else { + try { + await writeFile(file, content); + } catch (e) { + console.log(e); + } + } + } }; await create(); diff --git a/src/fs/delete.js b/src/fs/delete.js index a70b13766c..3919f20cb1 100644 --- a/src/fs/delete.js +++ b/src/fs/delete.js @@ -1,5 +1,35 @@ +import { unlink, access } from "node:fs/promises"; +import { URL, fileURLToPath } from "node:url"; + const remove = async () => { // Write your code here + const fileURL = new URL("./files/fileToRemove.txt", import.meta.url); + const filePath = fileURLToPath(fileURL); + const errorMessage = "FS operation failed"; + try { + //check if file exists + try { + await access(filePath); + } catch (e) { + throw new Error(errorMessage); + } + + //after ensuring in file existence try to delete it + //and handle if there is any error + try { + await unlink(filePath); + console.log("File deleted successfully"); + } catch (e) { + console.log(e); + } + } catch (e) { + //handle both of custom thrown error and uknown one + if (e instanceof Error && e.message === errorMessage) { + console.log(e.message); + } else { + console.log(e); + } + } }; 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 61% rename from src/fs/files/wrongFilename.txt rename to src/fs/files/properFilename.md index 38cca5db19..19f018e566 100644 --- a/src/fs/files/wrongFilename.txt +++ b/src/fs/files/properFilename.md @@ -1,3 +1,3 @@ # This is a file with a wrong filename -Hello from **markdown**! \ No newline at end of file +Hello from **markdown**! diff --git a/src/fs/list.js b/src/fs/list.js index 0c0fa21f7e..ae425f16e9 100644 --- a/src/fs/list.js +++ b/src/fs/list.js @@ -1,5 +1,26 @@ +import { readdir, access } from "node:fs/promises"; +import { URL, fileURLToPath } from "node:url"; + const list = async () => { // Write your code here + const directoryURL = new URL("./files/", import.meta.url); + const directory = fileURLToPath(directoryURL); + const errorMessage = "FS operation failed"; + try { + try { + await access(directory); + } catch (e) { + throw new Error(errorMessage); + } + const fileNames = await readdir(directory); + console.log(fileNames); + } catch (e) { + if (e instanceof Error && e.message === errorMessage) { + console.log(e.message); + } else { + console.log(e); + } + } }; await list(); diff --git a/src/fs/read.js b/src/fs/read.js index e3938be563..a7642f4d2f 100644 --- a/src/fs/read.js +++ b/src/fs/read.js @@ -1,5 +1,26 @@ +import { readFile, access } from "node:fs/promises"; +import { URL, fileURLToPath } from "node:url"; + const read = async () => { // Write your code here + const fileURL = new URL("./files/fileToRead.txt", import.meta.url); + const file = fileURLToPath(fileURL); + const errorMessage = "FS operation failed"; + try { + try { + await access(file); + } catch (e) { + throw new Error(errorMessage); + } + const contents = await readFile(file, { encoding: "utf8" }); + console.log(contents); + } catch (e) { + if (e instanceof Error && e.message === errorMessage) { + console.log(e.message); + } else { + console.log(e); + } + } }; await read(); diff --git a/src/fs/rename.js b/src/fs/rename.js index b1d65b0c86..88b7240ad5 100644 --- a/src/fs/rename.js +++ b/src/fs/rename.js @@ -1,5 +1,32 @@ +import { rename as renamePromise, access } from "node:fs/promises"; +import { URL, fileURLToPath } from "node:url"; + const rename = async () => { // Write your code here + const oldPathURL = new URL("./files/wrongFilename.txt", import.meta.url); + const newPathURL = new URL("./files/properFilename.md", import.meta.url); + const oldPath = fileURLToPath(oldPathURL); + const newPath = fileURLToPath(newPathURL); + const errorMessage = "FS operation failed"; + try { + try { + await access(oldPath); + } catch (e) { + throw new Error(errorMessage); + } + await access(newPath); + throw new Error(errorMessage); + } catch (e) { + if (e instanceof Error && e.message === errorMessage) { + console.log(e.message); + } else { + try { + await renamePromise(oldPath, newPath); + } catch (e) { + console.log(e); + } + } + } }; await rename(); diff --git a/src/hash/calcHash.js b/src/hash/calcHash.js index e37c17ed62..dbf897d486 100644 --- a/src/hash/calcHash.js +++ b/src/hash/calcHash.js @@ -1,5 +1,26 @@ +import { createHash } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { URL, fileURLToPath } from "node:url"; + const calculateHash = async () => { // Write your code here + const fileUrl = new URL( + "./files/fileToCalculateHashFor.txt", + import.meta.url, + ); + const filePath = fileURLToPath(fileUrl); + + const hash = createHash("sha256"); + + hash.on("readable", () => { + const data = hash.read(); + if (data) { + console.log(data.toString("hex")); + } + }); + + const fileStream = createReadStream(filePath); + fileStream.pipe(hash); }; await calculateHash(); diff --git a/src/modules/cjsToEsm.cjs b/src/modules/cjsToEsm.cjs deleted file mode 100644 index 089bd2db13..0000000000 --- a/src/modules/cjsToEsm.cjs +++ /dev/null @@ -1,34 +0,0 @@ -const path = require('node:path'); -const { release, version } = require('node:os'); -const { createServer: createServerHttp } = require('node:http'); - -require('./files/c.cjs'); - -const random = Math.random(); - -const unknownObject = random > 0.5 ? require('./files/a.json') : require('./files/b.json'); - -console.log(`Release ${release()}`); -console.log(`Version ${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'); -}); - -module.exports = { - unknownObject, - myServer, -}; diff --git a/src/modules/esm.mjs b/src/modules/esm.mjs new file mode 100644 index 0000000000..607b0e4f90 --- /dev/null +++ b/src/modules/esm.mjs @@ -0,0 +1,38 @@ +import { sep } 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"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const random = Math.random(); + +const unknownObject = await ( + random > 0.5 + ? import("./files/a.json", { with: { type: "json" } }) + : import("./files/b.json", { with: { type: "json" } }) +).then((module) => module.default); + +console.log(`Release ${release()}`); +console.log(`Version ${version()}`); +console.log(`Path segment separator is "${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 }; diff --git a/src/streams/files/fileToWrite.txt b/src/streams/files/fileToWrite.txt index e69de29bb2..2ec30825be 100644 --- a/src/streams/files/fileToWrite.txt +++ b/src/streams/files/fileToWrite.txt @@ -0,0 +1 @@ +Very well diff --git a/src/streams/read.js b/src/streams/read.js index e3938be563..dee73b81b4 100644 --- a/src/streams/read.js +++ b/src/streams/read.js @@ -1,5 +1,13 @@ +import { createReadStream } from "node:fs"; +import { URL, fileURLToPath } from "node:url"; const read = async () => { // Write your code here + const fileURL = new URL("./files/fileToRead.txt", import.meta.url); + const filePath = fileURLToPath(fileURL); + + const readableStream = createReadStream(filePath, { encoding: "utf-8" }); + + readableStream.pipe(process.stdout); }; await read(); diff --git a/src/streams/transform.js b/src/streams/transform.js index 9e6c15fe84..fa1f8c1c3a 100644 --- a/src/streams/transform.js +++ b/src/streams/transform.js @@ -1,5 +1,14 @@ +import { Transform } from "node:stream"; const transform = async () => { // Write your code here + const reverseStream = new Transform({ + transform(chunk, _, callback) { + const reversed = chunk.toString().split("").reverse().join(""); + callback(null, reversed); + }, + }); + + process.stdin.pipe(reverseStream).pipe(process.stdout); }; await transform(); diff --git a/src/streams/write.js b/src/streams/write.js index 84aa11e7cb..f8ba95089c 100644 --- a/src/streams/write.js +++ b/src/streams/write.js @@ -1,5 +1,13 @@ +import { createWriteStream } from "node:fs"; +import { URL, fileURLToPath } from "node:url"; const write = async () => { // Write your code here + const fileURL = new URL("./files/fileToWrite.txt", import.meta.url); + const filePath = fileURLToPath(fileURL); + + const writableStream = createWriteStream(filePath, { encoding: "utf-8" }); + + process.stdin.pipe(writableStream); }; await write(); diff --git a/src/wt/main.js b/src/wt/main.js index e2ef054d41..4ca43e6b17 100644 --- a/src/wt/main.js +++ b/src/wt/main.js @@ -1,5 +1,32 @@ +import { cpus } from "node:os"; +import { Worker } from "node:worker_threads"; +import { URL, fileURLToPath } from "node:url"; + const performCalculations = async () => { // Write your code here + const numCPUs = cpus().length; + const workerURL = new URL("./worker.js", import.meta.url); + const workerPath = fileURLToPath(workerURL); + + const promises = Array.from({ length: numCPUs }, (_, i) => { + const workerData = 10 + i; + const worker = new Worker(workerPath, { workerData }); + + return new Promise((resolve) => { + worker.on("message", (data) => { + resolve({ status: "resolved", data }); + }); + worker.on("error", () => { + resolve({ status: "error", data: null }); + }); + worker.on("exit", (code) => { + if (code !== 0) resolve({ status: "error", data: null }); + }); + }); + }); + + const resultsArray = await Promise.all(promises); + console.log(resultsArray); }; await performCalculations(); diff --git a/src/wt/worker.js b/src/wt/worker.js index 405595394d..ef15040e99 100644 --- a/src/wt/worker.js +++ b/src/wt/worker.js @@ -1,8 +1,14 @@ +import { parentPort, workerData } from "node:worker_threads"; // n should be received from main thread -const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2); +const nthFibonacci = (n) => + n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2); const sendResult = () => { // This function sends result of nthFibonacci computations to main thread + + const result = nthFibonacci(workerData); + + parentPort.postMessage(result); }; sendResult(); diff --git a/src/zip/compress.js b/src/zip/compress.js index d55209587e..50b2b3c5b9 100644 --- a/src/zip/compress.js +++ b/src/zip/compress.js @@ -1,5 +1,24 @@ +import { createReadStream, createWriteStream } from "node:fs"; +import { createGzip } from "node:zlib"; +import { pipeline } from "node:stream/promises"; +import { URL, fileURLToPath } from "node:url"; const compress = async () => { // Write your code here + const inputFileURL = new URL("./files/fileToCompress.txt", import.meta.url); + const input = fileURLToPath(inputFileURL); + const outputFileURL = new URL("./files/archive.gz", import.meta.url); + const output = fileURLToPath(outputFileURL); + + const gzip = createGzip(); + + const source = createReadStream(input); + const destination = createWriteStream(output); + try { + await pipeline(source, gzip, destination); + console.log("Compression complete!"); + } catch (err) { + console.error("Compression failed:", err); + } }; await compress(); diff --git a/src/zip/decompress.js b/src/zip/decompress.js index 8aaf26c8a4..15fc5aab0d 100644 --- a/src/zip/decompress.js +++ b/src/zip/decompress.js @@ -1,5 +1,25 @@ +import { createReadStream, createWriteStream } from "node:fs"; +import { createGunzip } from "node:zlib"; +import { pipeline } from "node:stream/promises"; +import { URL, fileURLToPath } from "node:url"; + const decompress = async () => { // Write your code here + const inputFileURL = new URL("./files/archive.gz", import.meta.url); + const input = fileURLToPath(inputFileURL); + + const outputFileURL = new URL("./files/fileToCompress.txt", import.meta.url); + const output = fileURLToPath(outputFileURL); + + const gunzip = createGunzip(); + const source = createReadStream(input); + const destination = createWriteStream(output); + try { + await pipeline(source, gunzip, destination); + console.log("Decompression complete!"); + } catch (err) { + console.error("Decompression failed:", err); + } }; await decompress(); diff --git a/src/zip/files/archive.gz b/src/zip/files/archive.gz new file mode 100644 index 0000000000..f04ad97dcf Binary files /dev/null and b/src/zip/files/archive.gz differ diff --git a/src/zip/files/fileToCompress.txt b/src/zip/files/fileToCompress.txt index 4d4efc82fe..c05cafdce9 100644 --- a/src/zip/files/fileToCompress.txt +++ b/src/zip/files/fileToCompress.txt @@ -1 +1 @@ -Compress me! \ No newline at end of file +Compress me!