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
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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 args = process.argv.slice(2);
const parsedArgs = {};

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

for (const [key, value] of Object.entries(parsedArgs)) {
console.log(`${key} is ${value}`);
}
};

parseArgs();
parseArgs();
10 changes: 8 additions & 2 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 = process.env;
const rssVars = Object.keys(envVars)
.filter(key => key.startsWith('RSS_'))
.map(key => `${key}=${envVars[key]}`)
.join('; ');

console.log(rssVars);
};

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

const scriptPath = path.resolve(import.meta.dirname, 'files', 'script.js');

const spawnChildProcess = async (args) => {
// Write your code here
const childProcess = spawn('node', [scriptPath, ...args], {
stdio: ['pipe', 'pipe', 'inherit']
});

process.stdin.pipe(childProcess.stdin);
childProcess.stdout.pipe(process.stdout);
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess([1, 2, 3]);
33 changes: 32 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
import { stat, cp } from 'node:fs/promises';
import path from 'node:path';

const copy = async () => {
// Write your code here
const sourceDir = path.resolve(import.meta.dirname, 'files');
const destinationDir = path.resolve(import.meta.dirname, 'files_copy');
const errorMessage = 'FS operation failed';

try {
const sourceStats = await stat(sourceDir);
if (!sourceStats.isDirectory()) {
throw new Error(errorMessage);
}
} catch {
throw new Error(errorMessage);
}

try {
const destStats = await stat(destinationDir);
if (destStats.isDirectory()) {
throw new Error(errorMessage);
}
} catch (err) {
if (err.code !== 'ENOENT') {
throw new Error(errorMessage);
}
}

try {
await cp(sourceDir, destinationDir, { recursive: true, errorOnExist: true, force: false });
} catch (error) {
throw new Error(errorMessage);
}
};

await copy();
23 changes: 21 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import { open } from 'node:fs/promises';
import path from 'node:path';

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

try {
const fileHandle = await open(filePath, 'wx');
const content = 'I am fresh and young';
try {
await fileHandle.writeFile(content, 'utf-8');
} finally {
await fileHandle.close();
}
} catch (err) {
const errorMessage = 'FS operation failed';
if (err.code === 'EEXIST') {
throw new Error(errorMessage);
}
throw err;
}
};

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

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

try {
await unlink(filePath);
} catch (error) {
const errorMessage = 'FS operation failed';
if (error.code === 'ENOENT') {
throw new Error(errorMessage);
}
}
};

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

const list = async () => {
// Write your code here
try {
const dirPath = path.resolve(import.meta.dirname, 'files');
const filenames = await readdir(dirPath);
console.log(filenames);
} catch (error) {
const errorMessage = 'FS operation failed';
throw new Error(errorMessage);
}
};

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

const read = async () => {
// Write your code here
const filePath = path.resolve(import.meta.dirname, 'files', 'fileToRead.txt');
try {
const data = await readFile(filePath, 'utf8');
console.log(data);
} catch (error) {
const errorMessage = 'FS operation failed';
throw new Error(errorMessage);
}
};

await read();
await read();
18 changes: 16 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { rename as renameFs } from 'node:fs/promises';
import path from 'node:path';

const rename = async () => {
// Write your code here
const basePath = path.resolve(import.meta.dirname, 'files');
const oldPath = path.resolve(basePath, 'wrongFilename.txt');
const newPath = path.resolve(basePath, 'properFilename.md');
const errorMessage = 'FS operation failed';

try {
await renameFs(oldPath, newPath);
} catch (err) {
if (err.code === 'ENOENT' || err.code === 'EEXIST') {
throw new Error(errorMessage);
}
}
};

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

const calculateHash = async () => {
// Write your code here
const filePath = path.resolve(import.meta.dirname, 'files', 'fileToCalculateHashFor.txt');
const hash = createHash('sha256');
const stream = createReadStream(filePath);

return new Promise((resolve, reject) => {
stream.on('data', (chunk) => {
hash.update(chunk);
});

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

stream.on('error', (error) => {
reject(error);
});
});
};

await calculateHash();
await calculateHash();
31 changes: 20 additions & 11 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
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 { fileURLToPath } from 'url';
import { dirname } from 'path';

import a from './files/a.json' with { type: 'json' };
import b from './files/b.json' with { type: 'json' };

const importC = async () => {
await import('./files/c.cjs');
};

await importC();

const random = Math.random();

let unknownObject;

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

console.log(`Release ${release()}`);
console.log(`Version ${version()}`);
console.log(`Path segment separator is "${path.sep}"`);

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

console.log(`Path to current file is ${__filename}`);
console.log(`Path to current directory is ${__dirname}`);

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

module.exports = {
unknownObject,
myServer,
};

export { unknownObject, myServer };
14 changes: 12 additions & 2 deletions src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { createReadStream } from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { pipeline } from 'node:stream/promises';

const filePath = path.resolve(import.meta.dirname, 'files', 'fileToRead.txt');

const read = async () => {
// Write your code here
const stream = createReadStream(filePath);
stream.on('end', () => process.stdout.write(os.EOL));

await pipeline(stream, process.stdout, {end: false});
};

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

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

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

reverseTransform.on('error', (err) => {
console.error(`Error in the stream: ${err.message}`);
});
};

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

const write = async () => {
// Write your code here
const filePath = path.resolve(import.meta.dirname, 'files', 'fileToWrite.txt');
const stream = createWriteStream(filePath);

process.stdin.pipe(stream);

await new Promise((resolve, reject) => {
stream.on('finish', resolve);
stream.on('error', reject);
});
};

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

const numCPUs = cpus().length;
const workerPath = path.resolve(import.meta.dirname, 'worker.js');
const initialData = 10;

const performCalculations = async () => {
// Write your code here
const workers = Array.from({ length: numCPUs }, (_, i) => {
return new Promise((resolve) => {
const worker = new Worker(workerPath, {
workerData: initialData + i,
});

worker.on('message', (msg) => {
resolve(msg);
});

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

const result = await Promise.all(workers);
console.log(result);
};

await performCalculations();
await performCalculations();
Loading