Skip to content
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
13 changes: 12 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);

const result = [];

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

result.push(`${propName} is ${value}`);
}

console.log(result.join(', '));
};

parseArgs();
9 changes: 8 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
const parseEnv = () => {
// Write your code here
const envVars = process.env;

const result = Object.entries(envVars)
.filter(([key]) => key.startsWith('RSS_'))
.map(([key, value]) => `${key}=${value}`)
.join('; ');

console.log(result);
};

parseEnv();
28 changes: 25 additions & 3 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const spawnChildProcess = async (args) => {
// Write your code here
const childScript = path.resolve(__dirname, 'files', 'script.js');

const child = spawn('node', [childScript, ...args], {
stdio: ['pipe', 'pipe', 'inherit'],
});

process.stdin.pipe(child.stdin);

child.stdout.pipe(process.stdout);

child.on('close', (code) => {
console.log(`\nChild process exited with code ${code}`);
});

child.on('error', (err) => {
console.error('Failed to start child process:', err);
});
};

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

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

const copy = async () => {
// Write your code here
try {
const src = path.resolve(__dirname, 'files');
const dest = path.resolve(__dirname, 'files_copy');

await cp(src, dest, {
recursive: true,
errorOnExist: true,
force: false,
});
} catch {
throw new Error('FS operation failed');
}
};

await copy();
15 changes: 14 additions & 1 deletion 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 path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const create = async () => {
// Write your code here
try {
const filePath = path.resolve(__dirname, 'files', 'fresh.txt');

await writeFile(filePath, 'I am fresh and young', { flag: 'wx' });
} catch {
throw new Error('FS operation failed');
}
};

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 { rm, access } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const remove = async () => {
// Write your code here
try {
const filePath = path.resolve(__dirname, 'files', 'fileToRemove.txt');

await access(filePath);

await rm(filePath);
} catch {
throw new Error('FS operation failed');
}
};

await remove();
1 change: 0 additions & 1 deletion src/fs/files/fileToRemove.txt

This file was deleted.

17 changes: 16 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { readdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const list = async () => {
// Write your code here
try {
const folderPath = path.resolve(__dirname, 'files');

const files = await readdir(folderPath);

console.log(files);
} catch {
throw new Error('FS operation failed');
}
};

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

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

const read = async () => {
// Write your code here
try {
const filePath = path.resolve(__dirname, 'files', 'fileToRead.txt');

const content = await readFile(filePath, 'utf-8');

console.log(content);
} catch {
throw new Error('FS operation failed');
}
};

await read();
23 changes: 22 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import { rename as fsRename, access } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const rename = async () => {
// Write your code here
try {
const srcPath = path.resolve(__dirname, 'files', 'wrongFilename.txt');
const destPath = path.resolve(__dirname, 'files', 'properFilename.md');

await access(srcPath);

try {
await access(destPath);
throw new Error();
} catch {}

await fsRename(srcPath, destPath);
} catch {
throw new Error('FS operation failed');
}
};

await rename();
28 changes: 27 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
import { createReadStream } from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const calculateHash = async () => {
// Write your code here
const filePath = path.resolve(
__dirname,
'files',
'fileToCalculateHashFor.txt',
);

return new Promise((resolve, reject) => {
const hash = createHash('sha256');
const stream = createReadStream(filePath);

stream.on('error', () => reject(new Error('FS operation failed')));

stream.on('data', (chunk) => hash.update(chunk));

stream.on('end', () => {
console.log(hash.digest('hex'));
resolve();
});
});
};

await calculateHash();
22 changes: 13 additions & 9 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
const path = require('node:path');
const { release, version } = require('node:os');
const { createServer: createServerHttp } = require('node:http');
import path from 'node:path';
import { release, version } from 'node:os';
import { createServer as createServerHttp } from 'node:http';
import { fileURLToPath } from 'node:url';

require('./files/c.cjs');
import './files/c.cjs';

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

const random = Math.random();

const unknownObject = random > 0.5 ? require('./files/a.json') : require('./files/b.json');
const unknownObject =
random > 0.5
? (await import('./files/a.json', { with: { type: 'json' } })).default
: (await import('./files/b.json', { with: { type: 'json' } })).default;

console.log(`Release ${release()}`);
console.log(`Version ${version()}`);
Expand All @@ -28,7 +35,4 @@ myServer.listen(PORT, () => {
console.log('To terminate it, use Ctrl+C combination');
});

module.exports = {
unknownObject,
myServer,
};
export { unknownObject, myServer };
Empty file removed src/streams/files/fileToWrite.txt
Empty file.
17 changes: 16 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { createReadStream } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const read = async () => {
// Write your code here
const filePath = path.resolve(__dirname, 'files', 'fileToRead.txt');

const readable = createReadStream(filePath);

readable.on('error', () => {
throw new Error('FS operation failed');
});

readable.pipe(process.stdout);
};

await read();
11 changes: 10 additions & 1 deletion src/streams/transform.js
Original file line number Diff line number Diff line change
@@ -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();
13 changes: 12 additions & 1 deletion src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { createWriteStream } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const write = async () => {
// Write your code here
const filePath = path.resolve(__dirname, 'files', 'fileToWrite.txt');

const writable = createWriteStream(filePath);

process.stdin.pipe(writable);
};

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

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

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

for (let i = 0; i < numCPUs; i++) {
const worker = new Worker(path.resolve(__dirname, 'worker.js'));
workers.push(worker);

const n = 10 + i;

const promise = new Promise((resolve) => {
worker.once('message', (msg) => resolve(msg));
worker.once('error', () => resolve({ status: 'error', data: null }));
});

worker.postMessage(n);
results.push(promise);
}

const finalResults = await Promise.all(results);
console.log(finalResults);

workers.forEach((w) => w.terminate());
};

await performCalculations();
25 changes: 22 additions & 3 deletions src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
// n should be received from main thread
const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2);
import { parentPort } from 'node:worker_threads';

const nthFibonacci = (n) =>
n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2);

let lastResult = null;

const sendResult = () => {
// This function sends result of nthFibonacci computations to main thread
if (parentPort && lastResult !== null) {
parentPort.postMessage(lastResult);
}
};

if (parentPort) {
parentPort.on('message', (n) => {
try {
const fib = nthFibonacci(n);
lastResult = { status: 'resolved', data: fib };
sendResult();
} catch (err) {
lastResult = { status: 'error', data: null };
sendResult();
}
});
}

sendResult();
Loading