Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cli functions #534

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
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
56 changes: 55 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,57 @@
# Node.js basics

## !!! Please don't submit Pull Requests to this repository !!!
Task: https://github.com/AlreadyBored/nodejs-assignments/blob/main/assignments/nodejs-basics/assignment.md

Done 07.10.2024 19:00 / deadline 08.10.2024 02:00

PR: https://github.com/AlreadyBored/node-nodejs-basics/pull/577

Score: 206 / 206

### File system (src/fs)

+6 create.js implemented properly

+10 copy.js implemented properly

+10 rename.js implemented properly

+6 delete.js implemented properly

+6 list.js implemented properly

+6 read.js implemented properly

### Command line interface(src/cli)

+6 env.js implemented properly

+6 args.js implemented properly

### Modules(src/modules)

+20 cjsToEsm.cjs refactored properly

### Hash (src/hash)
+10 calcHash.js implemented properly
### Streams (src/streams)
+10 read.js implemented properly

+10 write.js implemented properly

+10 transform.js implemented properly
### Zlib (src/zip)
+10 compress.js implemented properly

+10 decompress.js implemented properly
## Advanced Scope
### Worker Threads (src/wt)
+10 worker.js implemented properly

+30 main.js implemented properly
### Child Processes (src/cp)
+10 spawns child process

+10 child process stdin receives input from master process stdin

+10 child process stdout sends data to master process stdout
20 changes: 19 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
/*
* implement function that parses command line arguments (given in format --propName value --prop2Name value2,
* you don't need to validate it) and prints them to the console in the format
* propName is value, prop2Name is value2
*/

const parseArgs = () => {
// Write your code here
let result = "";
process.argv.slice(2).forEach(val => {
if (val.substring(0, 2) === "--") {
result += val.substring(2) + " is ";
} else {
result += val + ", ";
}
});
if (result[result.length - 2] === ",") {
result = result.substring(0, result.length - 2);
}

console.log(result);
};

parseArgs();
11 changes: 10 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
/*
* implement function that parses environment variables with prefix RSS_ and prints them to the console
* in the format RSS_name1=value1; RSS_name2=value2
*/

const parseEnv = () => {
// Write your code here
const result = Object.keys(process.env)
.filter(key => key.substring(0, 3) === 'RSS')
.map((key) => `${key}=${process.env[key]}`);

console.log(result);
};

parseEnv();
13 changes: 11 additions & 2 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
/*
* implement function spawnChildProcess that receives array of arguments args and creates child process
* from file script.js, passing these args to it.
* This function should create IPC-channel between stdin and stdout of master process and child process:
*/
import { spawn } from 'node:child_process';

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

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess( ['someArgument1', 'someArgument2' ]);
32 changes: 31 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
/*
* implement function that copies folder files files with all its content
* into folder files_copy at the same level
* (if files folder doesn't exists or files_copy has already been created
* Error with message FS operation failed must be thrown)
*/
import fs from "fs";

const copy = async () => {
// Write your code here
const dirSrc = "./src/fs/files";
const dirDest = "./src/fs/files_copy";

fs.cp(
dirSrc,
dirDest,
{
recursive: true,
force: false,
errorOnExist: true
},
(err) => {
if (err) {
if (err.code === "ERR_FS_CP_EEXIST") {
console.error("FS operation failed");
} else {
throw err;
}
} else {
console.log("Directory was copied");
}
}
);
};

await copy();
24 changes: 22 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
/*
* implement function that creates new file fresh.txt with content
* "I am fresh and young" inside of the files folder
* (if file already exists Error with message FS operation failed must be thrown)
*/
import fs from "fs";

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

if (fs.existsSync(filePath)) {
throw "FS operation failed"
} else {
fs.writeFile(
filePath,
"I am fresh and young",
(err) => {
if (err) throw err;
else console.log("File was created");
},
);
}
};

await create();
await create();
19 changes: 17 additions & 2 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
/*
* implement function that deletes file fileToRemove.txt
* (if there's no file fileToRemove.txt Error with message FS operation failed must be thrown)
*/
import fs from "fs";

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

if (!fs.existsSync(filePath)) {
throw "FS operation failed";
} else {
fs.rm(filePath, (err) => {
if (err) throw err;
else console.log('File was deleted!');
});
}
};

await remove();
await remove();
25 changes: 23 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
/*
* implement function that prints all array of filenames from files folder into console
* (if files folder doesn't exists Error with message FS operation failed must be thrown)
*/
import fs from "fs";

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

if (!fs.existsSync(dirPath)) {
throw "FS operation failed";
} else {
fs.readdir(
dirPath,
{recursive: true},
(err, files) => {
if (err) throw err;
else {
console.log(files);
}
},
);
}
};

await list();
await list();
23 changes: 21 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
/*
* implement function that prints content of the fileToRead.txt into console
* (if there's no file fileToRead.txt Error with message FS operation failed must be thrown)
*/
import fs from "fs";

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

if (!fs.existsSync(filePath)) {
throw "FS operation failed";
} else {
fs.readFile(
filePath,
"utf8",
(err, data) => {
if (err) throw err;
else console.log(data);
}
);
}
};

await read();
await read();
21 changes: 19 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
/*
* implement function that renames file wrongFilename.txt to properFilename with extension .md
* (if there's no file wrongFilename.txt or properFilename.md already exists
* Error with message FS operation failed must be thrown)
*/
import fs from "fs";

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

if (!fs.existsSync(oldName) || fs.existsSync(newName)) {
throw "FS operation failed";
} else {
fs.rename(oldName, newName, (err) => {
if (err) throw err;
else console.log('Rename complete!');
});
}
};

await rename();
await rename();
24 changes: 23 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
/*
* implement function that calculates SHA256 hash for file fileToCalculateHashFor.txt
* and logs it into console as hex using Streams API
*/
import { createHash } from 'node:crypto';
import fs from 'node:fs';

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

fs.readFile(
filePath,
"utf8",
(err, data) => {
if (err) throw err;
else content = data;
}
);
const result = createHash('sha256')
.update(content)
.digest('hex');

console.log(result);
};

await calculateHash();
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 path from 'node:path';
import { version, release } from 'node:os';
import http from 'node:http';
const __dirname = import.meta.dirname;
const __filename = import.meta.filename;
const { createServer: createServerHttp } = http;
import { createRequire } from "module";
const require = createRequire(import.meta.url);

import('./files/c.js');

const random = Math.random();

let unknownObject;

if (random > 0.5) {
unknownObject = require('./files/a.json');
} else {
unknownObject = 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');
});

export {
unknownObject,
myServer
};

21 changes: 20 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
/*
* implement function that reads file fileToRead.txt content using Readable Stream
* and prints it's content into process.stdout
*/
import fs from "fs";

const read = async () => {
// Write your code here
const filePath = "./src/streams/files/fileToRead.txt";
const readable = fs.createReadStream(
filePath,
{encoding: 'utf8'}
);

const chunks = [];

for await (const chunk of readable) {
chunks.push(Buffer.from(chunk));
}

const content = Buffer.concat(chunks).toString("utf-8");
process.stdout.write(`${content}\n`);
};

await read();
Loading