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
4 changes: 4 additions & 0 deletions helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import {dirname} from 'path'
import { fileURLToPath } from 'url';

export const getExecutedFileDirname = (metaUrl) => dirname(fileURLToPath(metaUrl));
15 changes: 13 additions & 2 deletions 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 propNamePrefix = '--'
const args = process.argv.reduce((acc, arg, index) => {
const nextElement = process.argv.length !== index+1 ? process.argv[index+1] : null;

if(arg.startsWith(propNamePrefix) && nextElement && !nextElement.startsWith(propNamePrefix)){
acc.push(`${arg} is ${nextElement}`)
}
return acc;
}, []).join(', ');

console.log(args);

};

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

console.log(availableEnv)
};

parseEnv();
parseEnv();
14 changes: 10 additions & 4 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
const spawnChildProcess = async (args) => {
// Write your code here
import path from 'path';
import { fork } from 'child_process';
import {getExecutedFileDirname} from "../../helpers.js";

const scriptFilePath = path.join(getExecutedFileDirname(import.meta.url), 'files', 'script.js');
const spawnChildProcess = async (...args) => {
const childProcess = fork(scriptFilePath, args, { silent: true });
process.stdin.pipe(childProcess.stdin);
childProcess.stdout.pipe(process.stdout);
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess("someArgument1", "someArgument2");
14 changes: 13 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import fs from 'fs/promises';
import {join} from 'path';
import {getExecutedFileDirname} from "../../helpers.js";
const copy = async () => {
// Write your code here
try {
const executedFileDirname = getExecutedFileDirname(import.meta.url);
const sourceFolderPath = join(executedFileDirname, 'files');
const destinationFolderPath = join(executedFileDirname, 'files_copy');

await fs.cp(sourceFolderPath, destinationFolderPath, { recursive: true, errorOnExist: true, force: false });
console.log('Copy operation successful');
} catch {
throw new Error('FS operation failed')
}
};

await copy();
15 changes: 13 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import fs from 'fs/promises';
import path from 'path';
import {getExecutedFileDirname} from "../../helpers.js";

const create = async () => {
// Write your code here
try {
const filePath = path.join(getExecutedFileDirname(import.meta.url), 'files', 'fresh.txt');
await fs.writeFile(filePath, 'I am fresh and young', {flag: 'wx'});
console.log('File created successfully!');
} catch( e) {
console.log('e ', e);
throw new Error('FS operation failed')
}
};

await create();
await create();
15 changes: 13 additions & 2 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import fs from 'fs/promises';
import path from 'path';
import {getExecutedFileDirname} from "../../helpers.js";
const remove = async () => {
// Write your code here
try {
const fileNamePath = path.join(getExecutedFileDirname(import.meta.url), 'files', 'fileToRemove.txt');
await fs.rm(fileNamePath);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('FS operation failed');
}
console.log(err);
}
};

await remove();
await remove();
13 changes: 11 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import fs from 'fs/promises';
import path from 'path';
import {getExecutedFileDirname} from "../../helpers.js";
const list = async () => {
// Write your code here
try {
const filesFolderPath = path.join(getExecutedFileDirname(import.meta.url), 'files');
const files = await fs.readdir(filesFolderPath);
console.log(files);
} catch {
throw new Error('FS operation failed');
}
};

await list();
await list();
13 changes: 11 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import fs from 'fs/promises'
import path from 'path'
import {getExecutedFileDirname} from "../../helpers.js";
const read = async () => {
// Write your code here
const filePath = path.join(getExecutedFileDirname(import.meta.url), 'files', 'fileToRead.txt');
try {
const content = await fs.readFile(filePath, { encoding: 'utf8' });
console.log(content);
} catch {
throw Error('FS operation failed');
}
};

await read();
await read();
27 changes: 25 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
import fs from 'fs/promises'
import path from 'path'
import {getExecutedFileDirname} from "../../helpers.js";
const rename = async () => {
// Write your code here
const executedFileDirname = getExecutedFileDirname(import.meta.url);
const wrongFileNamePath = path.join(executedFileDirname, 'files', 'wrongFilename.txt');
const properFileNamePath = path.join(executedFileDirname, 'files', 'properFilename.txt');

try {
await fs.access(wrongFileNamePath);

try {
await fs.access(properFileNamePath);
console.log('The file "properFilename.txt" is already exists');
throw new Error('FS operation failed');
} catch (err) {
if(err.code === 'ENOENT') {
await fs.rename(wrongFileNamePath, properFileNamePath)
} else {
throw err;
}
}
} catch (error) {
console.log('FS operation failed');
}
};

await rename();
await rename();
29 changes: 27 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
import fs from 'fs';
import {join} from 'path'
import crypto from 'crypto';
import {getExecutedFileDirname} from "../../helpers.js";

const calculateHash = async () => {
// Write your code here
const filePath = join(getExecutedFileDirname(import.meta.url), 'files', 'fileToCalculateHashFor.txt') ;
try {
const hash = crypto.createHash('sha256');
const readStream = fs.createReadStream(filePath);

readStream.on('data', (chunk)=> {
hash.update(chunk);
})

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

readStream.on('error', (err) => {
console.log(`Error reading file: ${err}`);
});

} catch (err) {
console.log('ERROR: ', err)
}

};

await calculateHash();
await calculateHash();
40 changes: 40 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import path from 'path';
import { release, version } from 'os';
import{ createServer as createServerHttp} from 'http';
import './files/c.js';

const random = Math.random();

let unknownObject;

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

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 fs from 'fs'
import {join} from "path";
import {getExecutedFileDirname} from "../../helpers.js";

const read = async () => {
// Write your code here
const filePath = join(getExecutedFileDirname(import.meta.url), 'files', 'fileToRead.txt');

const readStream = fs.createReadStream(filePath, { encoding: 'utf8' });

readStream.on("error", (err)=> console.error(err))

readStream.pipe(process.stdout)

};

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

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);
},
});

process.stdin.pipe(reverseTransform).pipe(process.stdout);

process.stdin.on("end", () => {
console.log("Stream ended.");
});

process.stdin.on("error", (err) => {
console.error("Error reading from stdin:", err);
});

reverseTransform.on("error", (err) => {
console.error("Error in Transform Stream:", err);
});
};

await transform();
await transform();
22 changes: 20 additions & 2 deletions src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import fs from 'fs'
import {join} from "path";
import {getExecutedFileDirname} from "../../helpers.js";
const write = async () => {
// Write your code here
const filePath = join(getExecutedFileDirname(import.meta.url), 'files', 'fileToWrite.txt');
try {

const writeStream = fs.createWriteStream(filePath, {encoding: 'utf8', flags: 'w'})

process.stdin.pipe(writeStream);

process.stdin.on('end', () => {
writeStream.end();
console.log('Finished writing to file.');
});

} catch (err) {
console.log('[ERROR] ', err)
}

};

await write();
await write();
26 changes: 24 additions & 2 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import os from "os";
import { Worker } from "worker_threads";
import { join } from "path";
import {getExecutedFileDirname} from "../../helpers.js";

const workerFilePath = join(getExecutedFileDirname(import.meta.url), "worker.js");

const performCalculations = async () => {
// Write your code here
const cpus = os.cpus();
let nthFibonacciNumber = 10;

const workersResults = await Promise.all(
cpus.map(() => {
return new Promise(resolve => {
const worker = new Worker(workerFilePath, {
workerData: nthFibonacciNumber++,
});
worker.on("message", data => resolve({ status: "resolved", data }));
worker.on("error", () => resolve({ status: "error", data: null }));
});
})
);

console.log(workersResults);
};

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

const sendResult = () => {
// This function sends result of nthFibonacci computations to main thread
if (Math.random() > 0.5) throw new Error("Something went wrong");

parentPort.postMessage(nthFibonacci(workerData));
};

sendResult();
sendResult();
Loading