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
6 changes: 5 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
const parseArgs = () => {
// Write your code here
const envVariables = process.env;
const envVariablesKeys = Object.keys(envVariables);
const newEnvVarKeys = envVariablesKeys.map(key => key.replace(/^--/, ''));
const filteredVariables = newEnvVarKeys.map(key => `${key} is ${envVariables[key]}`).join(', ');
console.log(filteredVariables);
};

parseArgs();
11 changes: 9 additions & 2 deletions 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 envVariables = process.env;
const envVariablesKeys = Object.keys(envVariables);
const filteredVariables = envVariablesKeys
.filter(key => key.startsWith('RSS_'))
.map(key => `${key}=${envVariables[key]}`)
.join('; ');
console.log(filteredVariables);
}

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

const spawnChildProcess = async (args) => {
// Write your code here
const child = spawn('node', ['./files/script.js', ...args], {
stdio: ['pipe', 'pipe', 'inherit', 'ipc']
});
process.stdin.pipe(child.stdin);
child.stdout.pipe(process.stdout);
child.on('error', (err) => {
console.error('Failed to start child process:', err);
});
child.on('exit', (code, signal) => {
if (code) {
console.log(`Child process exited with code ${code}`);
} else if (signal) {
console.log(`Child process killed with signal ${signal}`);
} else {
console.log('Child process exited successfully');
}
});
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess( ['someArgument1', 'someArgument2'] );
8 changes: 7 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import fs from 'node:fs';

const copy = async () => {
// Write your code here
fs.cp('./files', './files_copy', { recursive: true }, (err) => {
if (err) {
console.error('FS operation failed');
}
});
};

await copy();
11 changes: 10 additions & 1 deletion src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { appendFile } from 'node:fs';
import * as path from 'node:path';

const create = async () => {
// Write your code here
const folderPath = './files';
const filePath = path.join(folderPath, 'fresh.txt');
appendFile(filePath, 'I am fresh and young', function(err) {
if(err) {
console.error('FS operation failed');
}
});
};

await create();
6 changes: 5 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import fs from 'node:fs';

const remove = async () => {
// Write your code here
fs.unlink('./files/fileToRemove.txt', function(err) {
if(err) console.error('FS operation failed');
});
};

await remove();
9 changes: 8 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import fs from 'node:fs';

const list = async () => {
// Write your code here
const dirName = './files';
const filenames = fs.readdirSync(dirName);
filenames.forEach((file) => {
console.log(file);
});
if(!dirName) console.error('FS operation failed');
};

await list();
7 changes: 6 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import fs from 'node:fs';

const read = async () => {
// Write your code here
fs.readFile('./files/fileToRead.txt', 'utf8', (err, data) => {
if (err) console.error('FS operation failed');
console.log(data);
});
};

await read();
6 changes: 5 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import fs from 'node:fs';

const rename = async () => {
// Write your code here
fs.rename('./files/wrongFilename.txt', './files/properFilename.md', function(err) {
if(err) console.error('FS operation failed');
});
};

await rename();
15 changes: 14 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import fs from 'node:fs';
import crypto from 'crypto';

const secret = 'secretkey';

const calculateHash = async () => {
// Write your code here
const hmac = crypto.createHmac('sha256', secret);
const fileStream = fs.createReadStream('./files/fileToCalculateHashFor.txt');

for await (const chunk of fileStream) {
hmac.update(chunk);
}

const fileHmac = hmac.digest('hex');
console.log(`SHA256 HMAC of the file: ${fileHmac}`);
};

await calculateHash();
25 changes: 16 additions & 9 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
const path = require('path');
const { release, version } = require('os');
const { createServer: createServerHttp } = require('http');
require('./files/c');

import path from 'path';
import os from 'os';
import http from 'node:http';
import unknownObjectA from './files/a.json' assert {type: 'json'};
import unknownObjectB from './files/b.json' assert {type: 'json'};
import './files/c.js';
import { fileURLToPath } from 'url';

const { release, version } = os;
const random = Math.random();

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

let unknownObject;

if (random > 0.5) {
unknownObject = require('./files/a.json');
unknownObject = unknownObjectA;
} else {
unknownObject = require('./files/b.json');
unknownObject = unknownObjectB;
}

console.log(`Release ${release()}`);
Expand All @@ -20,7 +27,7 @@ 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) => {
const myServer = http.createServer((_, res) => {
res.end('Request accepted');
});

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

module.exports = {
export {
unknownObject,
myServer,
};
Expand Down
5 changes: 4 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import * as fs from 'node:fs';

const read = async () => {
// Write your code here
const readStream = fs.createReadStream('./files/fileToRead.txt');
readStream.pipe(process.stdout);
};

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

const transform = async () => {
// Write your code here
const reverseTextTransform = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().split('').reverse().join(''));
callback();
}
});

pipeline(
process.stdin,
reverseTextTransform,
process.stdout,
(err) => {
if (err) {
console.error('Pipeline failed:', err);
} else {
console.log('Pipeline completed successfully.');
}
}
);
};

await transform();
await transform();
12 changes: 11 additions & 1 deletion src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import fs from 'node:fs';

const write = async () => {
// Write your code here
const writableStream = fs.createWriteStream('fileToWrite.txt');
console.log('Please enter some text (press Ctrl+D to end input):');
process.stdin.pipe(writableStream);
writableStream.on('finish', () => {
console.log('Data has been written to fileToWrite.txt');
});
writableStream.on('error', (error) => {
console.error('An error occurred:', error.message);
});
};

await write();
42 changes: 41 additions & 1 deletion src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
import { Worker, isMainThread, parentPort } from 'worker_threads';
import os from 'os';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);

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

for (let i = 0; i < numCPUs; i++) {
const worker = new Worker(__filename, { workerData: 10 + i });

workers.push(worker);

worker.on('message', (result) => {
results.push({ status: 'resolved', data: result });

if (results.length === numCPUs) {
console.log('All workers finished:', results);
}
});

worker.on('error', (err) => {
results.push({ status: 'error', data: null });

if (results.length === numCPUs) {
console.log('All workers finished:', results);
}
});

worker.on('exit', (code) => {
if (code !== 0)
console.log(`Worker stopped with exit code ${code}`);
});
}
} else {
const { workerData } = require('worker_threads');
parentPort.postMessage(workerData);
}
};

await performCalculations();
39 changes: 33 additions & 6 deletions src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,35 @@
// n should be received from main thread
const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2);
import{ Worker, isMainThread, parentPort } from 'worker_threads';
import { fileURLToPath } from 'url';

const sendResult = () => {
// This function sends result of nthFibonacci computations to main thread
};
const __filename = fileURLToPath(import.meta.url);

sendResult();
if (isMainThread) {
// Main thread code
const worker = new Worker(__filename);

worker.on('message', (result) => {
console.log(`Fibonacci number: ${result}`);
worker.terminate();
});

worker.on('error', (err) => {
console.error(err);
worker.terminate();
});

// Send the number for which Fibonacci should be calculated
worker.postMessage(10);

} else {
// Worker thread code
const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2);

parentPort.on('message', (n) => {
const result = nthFibonacci(n);
sendResult(result);
});

const sendResult = (result) => {
parentPort.postMessage(result);
};
}
19 changes: 18 additions & 1 deletion src/zip/compress.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { createGzip } from 'node:zlib';
import { createReadStream, createWriteStream,} from 'node:fs';
import { promisify } from 'node:util';
import { pipeline } from 'node:stream';

const compress = async () => {
// Write your code here
const pipe = promisify(pipeline);

async function do_gzip(input, output) {
const gzip = createGzip();
const source = createReadStream(input);
const destination = createWriteStream(output);
await pipe(source, gzip, destination);
}
do_gzip('./files/fileToCompress.txt', 'archive.gz')
.catch((err) => {
console.error('An error occurred:', err);
process.exitCode = 1;
});
};

await compress();
Loading