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

Proff1991 node nodejs basics #569

Open
wants to merge 34 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
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
12 changes: 11 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
const prefix = '--';

const parseArgs = () => {
// Write your code here
const argsAcc = process.argv.slice(2).reduce((acc, value, index, array) => {
if (value.startsWith(prefix)) {
const formattedProp = value.replace(prefix, "") + " is " + array[index + 1];
return acc ? acc + ", " + formattedProp : formattedProp;
} else {
return acc;
}
}, "")
console.log(argsAcc);
};

parseArgs();
12 changes: 11 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
const prefix = 'RSS_';

const parseEnv = () => {
// Write your code here
const rssVars = Object.entries(process.env).reduce((acc, [key, value]) => {
if (key.startsWith(prefix)) {
return acc ? acc + "; " + key + '=' + value : key + '=' + value;
} else {
return acc;
}

}, "");
console.log(rssVars);
};

parseEnv();
19 changes: 15 additions & 4 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { fork as child_processFork } from 'child_process';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const scriptFile = 'script.js';
const scriptFolder = 'files';
const scriptFullPath = pathJoin(__dirname, scriptFolder, scriptFile);

const spawnChildProcess = async (args) => {
// Write your code here
};
const forkChildProcess = child_processFork(scriptFullPath, args.slice(2), {silent: true});
process.stdin.pipe(forkChildProcess.stdin);
forkChildProcess.stdout.pipe(process.stdout);
}

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess(process.argv);
35 changes: 32 additions & 3 deletions src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
const copy = async () => {
// Write your code here
import { stat as fsStat, copyFile as fsCopyFile, mkdir as fsMkdir, readdir } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const startFolder = 'files';
const addition = '_copy';
const newFolder = `${startFolder}${addition}`;
const startFolderPath = pathJoin(__dirname, startFolder);
const newFolderPath = pathJoin(__dirname, newFolder);
const errorMessage = 'FS operation failed';

async function isExists(path) {
try {
await fsStat(path);
return true;
} catch {
return false;
}
};

await copy();
const copy = async () => {
if (!!(await isExists(startFolderPath)) && !(await isExists(newFolderPath))) {
const arrayPromiseAll = await Promise.all([readdir(startFolderPath), fsMkdir(newFolderPath)]);
const copyingPromise = arrayPromiseAll[0].map(file => fsCopyFile(pathJoin(startFolderPath, file), pathJoin(newFolderPath, file)));
await Promise.all(copyingPromise);
} else {
throw new Error(errorMessage);
}
return;
}

await copy();
19 changes: 18 additions & 1 deletion src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { writeFile as fsWriteFile } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const folderPath = 'files';
const fileName = 'fresh.txt';
const fileContent = 'I am fresh and young';
const errorMessage = 'FS operation failed';
const fullPath = pathJoin(__dirname, folderPath, fileName);

const create = async () => {
// Write your code here
try {
await fsWriteFile(fullPath, fileContent, { flag: 'wx' });
} catch {
throw new Error(errorMessage);
}
return;
};

await create();
17 changes: 16 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { unlink as fsDeleteFile } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const currentFileName = 'fileToRemove.txt';
const folderName = 'files';
const errorMessage = 'FS operation failed';
const currentFilePath = pathJoin(__dirname, folderName, currentFileName);

const remove = async () => {
// Write your code here
try {
await fsDeleteFile(currentFilePath);
} catch {
throw new Error(errorMessage);
}
};

await remove();
19 changes: 17 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { readdir as fsReaddir } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const startFolder = 'files';
const errorMessage = 'FS operation failed';
const currentFilePath = pathJoin(__dirname, startFolder);

const list = async () => {
// Write your code here
};
try {
const insideContent = await fsReaddir(currentFilePath);
console.log(insideContent);
} catch {
throw new Error(errorMessage);
}
}

await list();
20 changes: 18 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { readFile as fsReadFile } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const currentFileName = 'fileToRead.txt';
const filePath = 'files';
const errorMessage = 'FS operation failed';
const currentFilePath = pathJoin(__dirname, filePath, currentFileName);

const read = async () => {
// Write your code here
};
try {
const insideContent = await fsReadFile(currentFilePath, 'utf-8');
console.log(insideContent);
} catch {
throw new Error(errorMessage);
}
}

await read();
28 changes: 27 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
import { rename as fsRename, stat as fsStat } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const currentFileName = 'wrongFilename.txt';
const folderName = 'files';
const newFileName = 'properFilename.md';
const errorMessage = 'FS operation failed';
const currentFilePath = pathJoin(__dirname, folderName, currentFileName);
const newFilePath = pathJoin(__dirname, folderName, newFileName);

async function isExists(path) {
try {
await fsStat(path);
return true;
} catch {
return false;
}
};

const rename = async () => {
// Write your code here
if (!!(await isExists(currentFilePath)) && !(await isExists(newFilePath))) {
await fsRename(currentFilePath, newFilePath);
} else {
throw new Error(errorMessage);
}
};

await rename();
19 changes: 17 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { createHash, createHash as cryptoCreateHash } from 'crypto';
import { readFile as fsReadFile } from 'fs/promises';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const filePath = 'files';
const fileName = 'fileToCalculateHashFor.txt';
const fileFullPath = pathJoin(__dirname, filePath, fileName);

const calculateHash = async () => {
// Write your code here
};
const content = await fsReadFile(fileFullPath);
const hashDataSrc = createHash('sha256').update(content);
const hashDataHex = hashDataSrc.digest('hex');
console.log(hashDataHex);
return hashDataHex;
}

await calculateHash();
21 changes: 13 additions & 8 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
const path = require('path');
const { release, version } = require('os');
const { createServer: createServerHttp } = require('http');
require('./files/c');
import path from 'path';
import { release, version } from 'os';
import { createServer as createServerHttp } from 'http';
import { createRequire } from "module";
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

import './files/c.js';

const random = Math.random();

Expand All @@ -21,7 +27,7 @@ console.log(`Path to current file is ${__filename}`);
console.log(`Path to current directory is ${__dirname}`);

const myServer = createServerHttp((_, res) => {
res.end('Request accepted');
res.end('Request accepted')
});

const PORT = 3000;
Expand All @@ -33,8 +39,7 @@ myServer.listen(PORT, () => {
console.log('To terminate it, use Ctrl+C combination');
});

module.exports = {
export {
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 as fsCreateReadStream } from 'fs';
import { pipeline } from 'stream/promises';
import { fileURLToPath } from 'node:url';
import { join as pathJoin, dirname as pathDirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const fileName = 'fileToRead.txt';
const filePath = 'files';
const fileFullPath = pathJoin(__dirname, filePath , fileName);

const read = async () => {
// Write your code here
await pipeline(fsCreateReadStream(fileFullPath), process.stdout);
};

await read();
await read();
21 changes: 18 additions & 3 deletions src/streams/transform.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { pipeline as streamPipeline } from 'stream/promises';
import { Transform } from 'stream';

function stringReverse(chunk) {
return chunk.toString().split('').reverse().join('')+"\n";
}

const transform = async () => {
// Write your code here
};

await transform();
const streamTransformingProcess = new Transform({
transform(chunk, encoding, callback) {
callback(null, stringReverse(chunk));
}
});

await streamPipeline(process.stdin, streamTransformingProcess, process.stdout);

}

await transform();
16 changes: 14 additions & 2 deletions src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { createWriteStream as fsCreateWriteStream } from 'fs';
import { pipeline as streamPipeline } from 'stream/promises';
import { fileURLToPath } from 'node:url';
import { join as pathJoin, dirname as pathDirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const fileName = 'fileToWrite.txt';
const filePath = 'files';
const fileFullPath = pathJoin(__dirname, filePath, fileName);

const write = async () => {
// Write your code here
};
const writableStream = fsCreateWriteStream(fileFullPath);
await streamPipeline(process.stdin, writableStream);
}

await write();
36 changes: 33 additions & 3 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
import { cpus } from 'os';
import { Worker } from 'worker_threads';
import { join as pathJoin, dirname as pathDirname } from 'path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = pathDirname(__filename);

const initNumber = 10;
const statusResolved = 'resolved';
const statusError = 'error';
const workerFile = 'worker.js';
const workerPath = pathJoin(__dirname, workerFile);

const performCalculations = async () => {
// Write your code here
};

await performCalculations();
const calculateNthFibonacci = workerData => new Promise(resolve => {
const runWorker = new Worker(workerPath, { workerData });
runWorker.on('message', data => resolve({ status: statusResolved, data }));
runWorker.on('error', data => resolve({ status: statusError, data: null }));
})

const cores = cpus();
const tasks = [];

for (let index = 0; index < cores.length; ++index) {
tasks.push(calculateNthFibonacci(index + initNumber));
}

const results = await Promise.all(tasks);

console.log(results);

}

await performCalculations();
Loading