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

Rsschool nodejs basics #591

Open
wants to merge 3 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
12 changes: 12 additions & 0 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
const parsedArgs = {};

for (let i = 0; i < args.length; i += 2) {
const propName = args[i].replace('--','');
const value = args[i + 1];
parsedArgs[propName] = value;
}

for (const prop in parsedArgs) {
console.log(`${prop} is ${parsedArgs[prop]}`);
}
};

parseArgs();
6 changes: 6 additions & 0 deletions src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
const parseEnv = () => {
// Write your code here
const envVars = Object.keys(process.env)
.filter(key => key.startsWith('RSS_'))
.map(key => `${key}=${process.env[key]}`)
.join("; ");

console.log(envVars);
};

parseEnv();
12 changes: 11 additions & 1 deletion src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { fileURLToPath } from 'url';
import path from 'path';
import { fork } from 'child_process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'files', 'script.js');

const spawnChildProcess = async (args) => {
// Write your code here
fork(filePath, args, { silent: false })
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess( ['arg1', 'arg2', 'arg3'] );
17 changes: 16 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourcePath = path.join(__dirname, 'files');
const destPath = path.join(__dirname, 'files_copy');

const copy = async () => {
// Write your code here
try {
await fs.cp(sourcePath, destPath, { recursive: true, force: false, errorOnExist: true });
} catch (error) {
throw new Error('FS operation failed');
}
};

await copy();
await copy();
14 changes: 14 additions & 0 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const pathToFreshFile = path.join(__dirname, 'files', 'fresh.txt');

const create = async () => {
// Write your code here
try {
await fs.writeFile(pathToFreshFile, 'I am fresh and young', { flag: 'wx' });
} catch (error) {
throw new Error('FS operation failed');
}

};

await create();
14 changes: 14 additions & 0 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const fileToRemove = path.join(__dirname, 'files', 'fileToRemove.txt');

const remove = async () => {
// Write your code here
try {
await fs.rm(fileToRemove);
} catch (error) {
throw new Error('FS operation failed');
}
};

await remove();
15 changes: 15 additions & 0 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourcePath = path.join(__dirname, 'files');

const list = async () => {
// Write your code here
try {
const fileList = await fs.readdir(sourcePath);
console.log(fileList);
} catch (error) {
throw new Error('FS operation failed');
}
};

await list();
15 changes: 15 additions & 0 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const pathToFileToRead = path.join(__dirname, 'files', 'fileToRead.txt');

const read = async () => {
// Write your code here
try {
const content = await fs.readFile(pathToFileToRead, { encoding: 'utf8' });
console.log(content);
} catch (error) {
throw new Error('FS operation failed');
}
};

await read();
15 changes: 15 additions & 0 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const pathToWrongFile = path.join(__dirname, 'files', 'wrongFilename.txt');
const pathToProperFile = path.join(__dirname, 'files', 'properFilename.md');

const rename = async () => {
// Write your code here
try {
await fs.rename(pathToWrongFile, pathToProperFile);
} catch (error) {
throw new Error('FS operation failed');
}
};

await rename();
13 changes: 13 additions & 0 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import path from 'path';
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import { createHash } from 'crypto';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'files', 'fileToCalculateHashFor.txt');

const calculateHash = async () => {
// Write your code here
const fileContent = await readFile(filePath);
const hash = createHash('sha256').update(fileContent).digest('hex');
console.log(`SHA256 hash: ${hash}`);
};

await calculateHash();
21 changes: 9 additions & 12 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
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 './files/c';

const random = Math.random();

let unknownObject;

if (random > 0.5) {
unknownObject = require('./files/a.json');
unknownObject = await import('./files/a.json', { assert: { type: "json" } });
} else {
unknownObject = require('./files/b.json');
unknownObject = await import('./files/b.json', { assert: { type: "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}`);
console.log(`Path to current file is ${import.meta.url}`);
console.log(`Path to current directory is ${new URL('.', import.meta.url).pathname}`);

const myServer = createServerHttp((_, res) => {
res.end('Request accepted');
Expand All @@ -33,8 +33,5 @@ myServer.listen(PORT, () => {
console.log('To terminate it, use Ctrl+C combination');
});

module.exports = {
unknownObject,
myServer,
};
export { unknownObject, myServer };

14 changes: 13 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { fileURLToPath } from 'url';
import path from 'path';
import { createReadStream } from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'files', 'fileToRead.txt');

const read = async () => {
// Write your code here
// Write your code here
const readStream = createReadStream(filePath, 'utf8');
readStream.pipe(process.stdout);

};

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

const transform = async () => {
// Write your code here
const reverseTransform = new Transform({
transform(chunk, encoding, callback) {
const reversedChunk = chunk.toString().split('').reverse().join('');
callback(null, reversedChunk + '\n');
}
});

await pipeline(process.stdin, reverseTransform, process.stdout);
};

await transform();
11 changes: 11 additions & 0 deletions src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { fileURLToPath } from 'url';
import path from 'path';
import { createWriteStream } from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'files', 'fileToWrite.txt')

const write = async () => {
// Write your code here
const writeStream = createWriteStream(filePath);
process.stdin.pipe(writeStream);
};

await write();
30 changes: 30 additions & 0 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
import { fileURLToPath } from 'url';
import path from 'path';
import { cpus } from 'os';
import { Worker } from 'worker_threads';


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'worker.js');

const performCalculations = async () => {
// Write your code here
const numCores = cpus().length;
const workers = [];

const createWorker = (data) => {
return new Promise((resolve) => {
const worker = new Worker(filePath, {workerData: data});

worker.on('message', (data) => resolve({status: 'resolved', data}));
worker.on('error', () => resolve({status: 'error', data: null}))
});
}

for (let i = 0; i < numCores; i++) {
workers.push(createWorker(i + 10));
}

const workerResults = await Promise.all(workers);

console.log(workerResults);
};

await performCalculations();
3 changes: 3 additions & 0 deletions src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { parentPort, workerData } from 'worker_threads';

// 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
parentPort.postMessage(nthFibonacci(workerData));
};

sendResult();
20 changes: 20 additions & 0 deletions src/zip/compress.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
import { fileURLToPath } from 'url';
import path from 'path';
import { createReadStream, createWriteStream } from 'fs';
import { pipeline } from 'stream';
import { createGzip } from 'zlib';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const fileToCompress = path.join(__dirname, 'files', 'fileToCompress.txt');
const archiveFile = path.join(__dirname, 'files', 'archive.gz');

const readStream = createReadStream(fileToCompress);
const writeStream = createWriteStream(archiveFile);

const compress = async () => {
// Write your code here
pipeline(readStream,
createGzip(),
writeStream,
(error) => console.error(error)
);
};

await compress();
Loading