Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f2ec92b
init: start nodejs-basics task
Jun 14, 2023
3fbef6e
feat: implement create file function
wishyouwell13 Jun 16, 2023
09d1225
feat: implement copy folder function
wishyouwell13 Jun 16, 2023
0019311
fix: remove separator from path
wishyouwell13 Jun 16, 2023
b463293
refactor: add exists function to helpers
wishyouwell13 Jun 16, 2023
a7891ed
refactor: add helpers
wishyouwell13 Jun 16, 2023
6f9f2c8
feat: implement rename file function
wishyouwell13 Jun 16, 2023
6478e6e
fix: add await before async function exists
wishyouwell13 Jun 16, 2023
c8c4310
feat: implement delete file function
wishyouwell13 Jun 16, 2023
ea245d4
feat: implement function that prints all array of filenames
wishyouwell13 Jun 16, 2023
0c5c20a
feat: implement function that prints content of file
wishyouwell13 Jun 16, 2023
3ac1b74
feat: implement function that parses environment variables
wishyouwell13 Jun 16, 2023
3e7a6ac
feat: implement function that parses command line arguments
wishyouwell13 Jun 16, 2023
dbff5e6
refactor: rewrite to equivalent in ECMAScript notation
wishyouwell13 Jun 16, 2023
acea378
feat: implemet calcHash function
wishyouwell13 Jun 17, 2023
f6404ac
feat: implement file reading with stream
wishyouwell13 Jun 17, 2023
2cb02d6
feat: implement write data to file with stream
wishyouwell13 Jun 17, 2023
567fdd2
feat: implement transform output string with streams
wishyouwell13 Jun 17, 2023
4958cbd
feat: implement function to compress file
wishyouwell13 Jun 17, 2023
e006536
feat: implement decompress function
wishyouwell13 Jun 17, 2023
376e04b
feat: implement calculations with worker_thread
wishyouwell13 Jun 18, 2023
e199a77
feat: implement task about creating child process
wishyouwell13 Jun 18, 2023
ce8c4c0
fix: use spawn instead of fork for cp task
wishyouwell13 Jun 19, 2023
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: 10 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
const parsedArgs = [];

for (let i = 0; i < args.length; i += 2) {
const [prop, value] = [args[i], args[i + 1]];
const str = `${prop.replace(/-/g, '')} is ${value}`;
parsedArgs.push(str);
}
console.log(parsedArgs.join(', '));
};

parseArgs();
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 result = [];
for (const [envKey, envValue] of Object.entries(process.env)) {
if (/^RSS_/.test(envKey)) {
const str = `${envKey}=${envValue}`;
result.push(str);
}
}
console.log(result.join('; '));
};

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

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'files', 'script.js');

const spawnChildProcess = async (args) => {
// Write your code here
const options = {
stdio: [0, 1, 2, 'ipc'],
};
spawn('node', [filePath, ...args], options);
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess(['1', '23', 'tt']);
26 changes: 24 additions & 2 deletions src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
const copy = async () => {
// Write your code here
import { cp } from 'fs/promises';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

import { exists } from './utils/helpers';

const __dirname = dirname(fileURLToPath(import.meta.url));
const path = join(__dirname, 'files');
const copyPath = join(__dirname, 'files_copy');

const copy = async (src = path, dest = copyPath) => {
try {
const isDestExists = await exists(dest);
const isSrcExists = await exists(src);

if (isDestExists || !isSrcExists) throw new Error('FS operation failed');

await cp(path, dest, {
recursive: true,
force: false,
});
} catch (e) {
console.error(e.message);
}
};

await copy();
20 changes: 18 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { writeFile } from 'fs/promises';

import { exists } from './utils/helpers';

const __dirname = dirname(fileURLToPath(import.meta.url));
const pathToFile = join(__dirname, 'files', 'fresh.txt');
const content = 'I am fresh and young';

const create = async () => {
// Write your code here
try {
const isExists = await exists(pathToFile);
if (isExists) throw new Error('FS operation failed');
await writeFile(pathToFile, content, { flag: 'wx' });
} catch (e) {
console.error(e.message);
}
};

await create();
await create();
21 changes: 17 additions & 4 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
const remove = async () => {
// Write your code here
};
import { unlink } from 'fs/promises';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';

import { exists } from './utils/helpers.js';

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

const remove = async (filename = 'fileToRemove.txt') => {
try {
const path = join(__dirname, 'files', filename);
if (!(await exists(path))) throw new Error('FS operation failed');
await unlink(path);
} catch (e) {
console.error(e.message);
}
};
await remove();
18 changes: 16 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { readdir } from 'fs/promises';
import { exists } from './utils/helpers.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const folder = join(__dirname, 'files');

const list = async () => {
// Write your code here
try {
if (!(await exists(folder))) throw new Error('FS operation failed');
const files = await readdir(folder);
for (const file of files) console.log(file);
} catch (err) {
console.error(err.message);
}
};

await list();
await list();
21 changes: 19 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

import { exists } from './utils/helpers.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'files', 'fileToRead.txt');

const read = async () => {
// Write your code here
try {
if (!(await exists(filePath))) throw new Error('FS operation failed');
const contents = await readFile(filePath, {
encoding: 'utf8',
});
console.log(contents);
} catch (err) {
console.error(err.message);
}
};

await read();
await read();
25 changes: 23 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import { fileURLToPath } from 'url';
import { dirname, join, parse, basename } from 'path';
import { rename as fsRename } from 'fs/promises';

import { exists } from './utils/helpers.js';

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

const rename = async () => {
// Write your code here
try {
const path = join(__dirname, 'files', 'wrongFilename.txt');
const filename = basename(path, '.txt');
const target = join(parse(path).dir, filename + '.md');

const isDestExists = await exists(path);
const isSrcExists = await exists(target);

if (isSrcExists || !isDestExists) throw new Error('FS operation failed');

await fsRename(path, target);
} catch (e) {
console.error(e.message);
}
};

await rename();
await rename();
12 changes: 12 additions & 0 deletions src/fs/utils/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { access } from 'fs/promises';

// Function Asynchronously Check if a File Exists
// https://futurestud.io/tutorials/node-js-check-if-a-file-exists
export async function exists(path) {
try {
await access(path);
return true;
} catch {
return false;
}
}
14 changes: 12 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { createHash } from 'node:crypto';
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'files', 'fileToCalculateHashFor.txt');

const calculateHash = async () => {
// Write your code here
const fileData = await readFile(filePath, { encoding: 'utf-8' });
const fileHash = createHash('sha256').update(fileData).digest('hex');
console.log(fileHash);
};

await calculateHash();
await calculateHash();
31 changes: 31 additions & 0 deletions src/modules/cjsToEsm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { sep, dirname, basename } from 'path';
import { release, version } from 'os';
import { createServer as createServerHttp } from 'http';
import { fileURLToPath } from 'url';

import dataA from './files/a.json' assert { type: 'json' };
import dataB from './files/b.json' assert { type: 'json' };
import './files/c.js';

const PORT = 3000;
const unknownObject = Math.random() > 0.5 ? dataA : dataB;
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

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

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

const myServer = createServerHttp((_, res) => {
res.end('Request accepted');
}).listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
console.log('To terminate it, use Ctrl+C combination');
});

console.log(unknownObject);

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 { fileURLToPath } from 'url';
import { dirname, join } from 'path';

// https://nodejs.org/dist/latest-v18.x/docs/api/stream.html#streampipelinesource-transforms-destination-options
import { pipeline } from 'node:stream/promises';
import { createReadStream } from 'node:fs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'files', 'fileToRead.txt');

const read = async () => {
// Write your code here
await pipeline(createReadStream(filePath), process.stdout);
};

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

const readable = process.stdin;
const writable = process.stdout;

const transformStream = new Transform({
transform(chunk, enc, cb) {
const chunkStringified = chunk.toString().trim();
const reversedChunk = chunkStringified.split('').reverse().join('');
this.push(reversedChunk + '\n');
cb();
},
});

const transform = async () => {
// Write your code here
try {
await pipeline(readable, transformStream, writable);
} catch (err) {
console.err(err.message);
}
};

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

// https://nodejs.org/dist/latest-v18.x/docs/api/stream.html#streampipelinesource-transforms-destination-options
import { pipeline } from 'node:stream/promises';
import { createWriteStream } from 'node:fs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'files', 'fileToWrite.txt');

const write = async () => {
// Write your code here
const stream = createWriteStream(filePath, { flags: 'w' });
// process.stdin.pipe(stream);
await pipeline(process.stdin, stream);
};

await write();
await write();
30 changes: 28 additions & 2 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { cpus } from 'os';
import { log } from 'console';

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'worker.js');

const OFFSET = 10;

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

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

const performCalculations = async () => {
// Write your code here
try {
const cores = cpus().length;
const result = await Promise.all(Array.from({ length: cores }, (_, idx) => createWorker(idx)));
console.log(result);
} catch (err) {
console.error(err);
}
};

await performCalculations();
await performCalculations();
7 changes: 4 additions & 3 deletions src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
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 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();
sendResult();
Loading