Skip to content
2 changes: 0 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
# Node.js basics

## !!! Please don't submit Pull Requests to this repository !!!
31 changes: 29 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
import { argv } from "node:process";

const parseArgs = () => {
// Write your code here
//index 0: node.exe
//index 1: src\cli\args.js
argv.splice(0, 2);

const argvStrings = extractArgs(argv);
const resultString = argvStrings.join(", ");

console.log(resultString);
};

/** accepts arrays of arguments (string[]) and extracts key-value pairs
* @returns new arrays of strings in format: '<key> is <value>'
*/
const extractArgs = (argv) => {
const argKeyPrefix = "--";
//array of strings, each item represents each pair of <arg key, arg value>
const result = [];

argv.forEach((str, index) => {
if (str.startsWith(argKeyPrefix)) {
const key = str.slice(argKeyPrefix.length, str.length);
result.push(`${key} is ${argv[index + 1]}`);
}
});

return result;
};

parseArgs();
parseArgs();
20 changes: 18 additions & 2 deletions src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { env } from "node:process";

/*
to test this function you can execute(tested on windows, powershell):
> $env:RSS_name1="value1"; $env:RSS_name2="value2"; $env:RSS_name3="another_value"

to remove previously declared variables execute:
> $env:RSS_name1=''; $env:RSS_name2=''; $env:RSS_name3=''
*/

const parseEnv = () => {
// Write your code here
const keyPrefix = "RSS_";

const varNames = Object.keys(env).filter((key) => key.startsWith(keyPrefix));
const varPairs = varNames.map((name) => `${name}=${env[name]}`);
const result = varPairs.join("; ");

console.log(result);
};

parseEnv();
parseEnv();
24 changes: 21 additions & 3 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
import { fork } from "node:child_process";

const spawnChildProcess = async (args) => {
// Write your code here
const child = fork("./src/cp/files/script.js", args);

process.stdin.onmessage = (data) => {
child.send(data);
};

child.on("message", (message) => {
console.log(`Received from child process: ${message}`);
});

child.on("close", function (code) {
console.log(`child process finished with code: ${code}`);
});
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
// tested with such command:
// > npm run cp --some-arg value1 --other 1337 --arg2 42
// spawnChildProcess(process.argv.slice(2));

// or comment line above and uncomment below one:
spawnChildProcess(["value1", 1337, 42]);
10 changes: 6 additions & 4 deletions src/cp/files/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ console.log(`Total number of arguments is ${args.length}`);
console.log(`Arguments: ${JSON.stringify(args)}`);

const echoInput = (chunk) => {
const chunkStringified = chunk.toString();
if (chunkStringified.includes('CLOSE')) process.exit(0);
process.stdout.write(`Received from master process: ${chunk.toString()}\n`)
const chunkStringified = chunk.toString();
if (chunkStringified.includes("CLOSE")) process.exit(0);
process.stdout.write(`Received from master process: ${chunk.toString()}\n`);
//send response to parent
process.send(`Received from master process: ${chunk.toString()}\n`);
};

process.stdin.on('data', echoInput);
process.stdin.on("data", echoInput);
15 changes: 14 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { cp } from "node:fs/promises";
import { isFileExists } from "./utils.js";

const copy = async () => {
// Write your code here
const src = "src/fs/files";
const dst = src + "_copy";
const options = { recursive: true };

const isSrcExists = await isFileExists(src);
const isDstExists = await isFileExists(dst);

if (!isSrcExists || isDstExists) {
throw new Error("FS operation failed");
}
await cp(src, dst, options);
};

await copy();
17 changes: 15 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { writeFile } from "node:fs/promises";
import { isFileExists } from "./utils.js";

const create = async () => {
// Write your code here
const src = "src/fs/files/fresh.txt";
const content = "I am fresh and young";

const exists = await isFileExists(src);

if (exists) {
throw new Error("FS operation failed");
}

const data = new Uint8Array(Buffer.from(content));
await writeFile(src, data);
};

await create();
await create();
15 changes: 13 additions & 2 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { rm } from "node:fs/promises";
import { isFileExists } from "./utils.js";

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

const exists = await isFileExists(src);

if (!exists) {
throw new Error("FS operation failed");
}

await rm(src);
};

await remove();
await remove();
16 changes: 14 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { readdir } from "node:fs/promises";
import { isFileExists } from "./utils.js";

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

const exists = await isFileExists(src);

if (!exists) {
throw new Error("FS operation failed");
}

const files = await readdir(src);
for (const file of files) console.log(file);
};

await list();
await list();
16 changes: 14 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { isFileExists } from "./utils.js";
import { readFile } from "node:fs/promises";

const read = async () => {
// Write your code here
const src = "src/fs/files/fileToRead.txt";
const options = { encoding: "utf8" };

const exists = await isFileExists(src);
if (!exists) {
throw new Error("FS operation failed");
}

const content = await readFile(src, options);
console.log(content);
};

await read();
await read();
18 changes: 16 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { rename as fsRename } from "node:fs/promises";
import { isFileExists } from "./utils.js";

const rename = async () => {
// Write your code here
const path = "src/fs/files/";
const src = path + "wrongFilename.txt";
const dst = path + "properFilename.md";

const isSrcExists = await isFileExists(src);
const isDstExists = await isFileExists(dst);

if (!isSrcExists || isDstExists) {
throw new Error("FS operation failed");
}

await fsRename(src, dst);
};

await rename();
await rename();
11 changes: 11 additions & 0 deletions src/fs/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { access, constants } from "node:fs/promises";

/** checks if given file exists */
export const isFileExists = async (filepath) => {
try {
await access(filepath, constants.F_OK);
return true;
} catch {
return false;
}
};
18 changes: 16 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { readFile } from "node:fs/promises";
//dynamic import
const { createHash } = await import("node:crypto");

const calculateHash = async () => {
// Write your code here
const src = "src/hash/files/fileToCalculateHashFor.txt";
const hash = createHash("sha256");
const digestFormat = "hex";

try {
const content = await readFile(src);
hash.update(content);
console.log(hash.digest(digestFormat));
} catch (err) {
console.log(err);
}
};

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

This file was deleted.

45 changes: 45 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import * as path from "node:path";
import { release, version } from "node:os";
import { createServer as createServerHttp } from "node:http";
import {} from "./files/c.js";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
import { readFile } from "node:fs/promises";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const options = { encoding: "utf8" };
const random = Math.random();

let unknownObject;

if (random > 0.5) {
unknownObject = await readFile(__dirname + "/files/a.json", options);
} else {
unknownObject = await readFile(__dirname + "/files/b.json", options);
}

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");
});

export default {
unknownObject,
myServer,
};
15 changes: 13 additions & 2 deletions src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { createReadStream } from "node:fs";

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

stream.on("data", (data) => {
process.stdout.write(data);
});

stream.on("error", function (error) {
console.log(`error: ${error.message}`);
});
};

await read();
await read();
Loading