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
9 changes: 7 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
const parseArgs = () => {
// Write your code here
};
const argvList = process.argv.slice(2);
let str = '';
for (let i = 0; i < argvList.length; i += 2) {
str += `${argvList[i].slice(2)} is ${argvList[i + 1]}, `;
}
console.log(str.slice(0, str.length - 2));
}

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 rssList = Object.entries(process.env).reduce((acc, [key, value]) => {
if (key.startsWith('RSS_')) {
acc.push(`${key}=${value}`)
}
return acc;
}, [])

console.log(rssList.reverse().join('; '));
}

parseEnv();
21 changes: 16 additions & 5 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
const spawnChildProcess = async (args) => {
// Write your code here
};
import { fork } from 'child_process'
import { __dirname } from '../utils.js'
import { join } from 'path'

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
const spawnChildProcess = async (args=[]) => {
const myChildProcess = fork(join(__dirname, 'cp', 'files', 'script.js'),args, {stdio: ['pipe', 'pipe', 'inherit', 'ipc']}
)

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

myChildProcess.on('exit', (msg) => {
console.log(`Child process exited with code ${msg}`)
})
}

spawnChildProcess(['one', 'two', 'three'])
30 changes: 29 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,33 @@
import { join } from 'path';
import { __dirname } from '../utils.js';
import { readdir, mkdir, copyFile, unlink } from 'fs/promises';
import { existsSync } from 'fs';

const copy = async () => {
// Write your code here

const fileCopy = join(__dirname, 'fs/files_copy');
const dir = join(__dirname, 'fs/files');

try {
if (existsSync(fileCopy) || !existsSync(dir)) {
throw new Error('FS operation failed')
}

await mkdir(fileCopy);
const files = await readdir(dir);
const copiedFiles = await readdir(fileCopy);
if (copyFile.length !== 0) {
for (const file of copiedFiles) {
unlink(join(__dirname, 'fs/files-copy', file));
}
}
for (const file of files) {
await copyFile(join(__dirname, 'fs/files', file), join(fileCopy, file));
}
console.log('Files copied');
} catch (err) {
console.error(err)
}
};

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 { join } from 'path';
import {__dirname} from '../utils.js';
import { createWriteStream, existsSync } from 'fs';

const create = async () => {
// Write your code here
};

const file = join(__dirname, 'fs/files/fresh.txt');
const data = 'I am fresh and young';
if (existsSync(file)) {
throw new Error('FS operation failed');
}
let wstream = createWriteStream(file);

wstream.on('error', (err) => console.log(`Err: ${err}`));
wstream.on('finish', () => console.log('Create'));

wstream.write(data);
wstream.end();
}

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

const remove = async () => {
// Write your code here
};
const file = join(__dirname, 'fs/files/fileToRemove.txt');
try {
if (!existsSync(file)) {
throw new Error('FS operation failed');
}
await unlink(file);
} catch (error) {
throw error;
}
}

await remove();
20 changes: 18 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { readdir } from 'fs/promises'
import { __dirname } from '../utils.js'
import { join } from 'path'
import { existsSync } from 'fs'

const list = async () => {
// Write your code here
};
try {
const folder = join(__dirname, 'fs', 'files');

if (!existsSync(folder)) {
throw new Error('FS operation failed');
}

const files = await readdir(folder);
console.log(files);
} catch (error) {
throw error;
}
}

await list();
17 changes: 15 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { createReadStream, existsSync } from 'fs';
import { join } from 'path';
import { __dirname } from '../utils.js';

const read = async () => {
// Write your code here
};
const file = join(__dirname, 'fs', 'files', 'fileToRead.txt');
if (!existsSync(file)) {
throw new Error('FS operation failed');
}
const readStream = createReadStream(file,'utf8');

readStream.on('data', (data) => console.log(data));
readStream.on('error', (error) => console.log('Error', error.message));

}

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 setNewName } from 'fs/promises'
import { __dirname } from '../utils.js'
import { join } from 'path'
import { existsSync } from 'fs'

const rename = async () => {
// Write your code here
};
const oldFile = join(__dirname, 'fs', 'files', 'wrongFilename.txt');
const newFile = join(__dirname, 'fs', 'files', 'properFilename.md');
try {
if (!existsSync(oldFile) || existsSync(newFile)) {
throw new Error('FS operation failed');
}
await setNewName(oldFile, newFile);
} catch (error) {
throw error;
}
}

await rename();
22 changes: 20 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import { createHash} from 'crypto';
import { createReadStream } from 'fs';
import { join } from 'path';
import { __dirname } from '../utils.js';

const calculateHash = async () => {
// Write your code here
};
const file = join(__dirname, 'hash', 'files', 'fileToCalculateHashFor.txt');
const sha256Hasher = createHash('sha256');

const readStream = createReadStream(file, 'utf-8');

return new Promise((resolvePromise, reject) => {
readStream.on('data', chunk => sha256Hasher.update(chunk));
readStream.on('end', () => {
const digest = sha256Hasher.digest('hex');
console.log(digest);
resolvePromise(digest);
});
readStream.on('error', reject);
});
}

await calculateHash();
37 changes: 37 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import path from 'path';
import { release, version } from 'os';
import { createServer as createServerHttp } from 'http';
import {__dirname, __filename} from '../utils.js';
import * as objectA from './files/a.json' with { type: 'json' };
import * as objectB from './files/b.json' with { type: 'json' };
import './files/c.cjs';

const random = Math.random();

let unknownObject;

if (random > 0.5) {
unknownObject = objectA;
} else {
unknownObject = objectB;
}

console.log(`Release ${release()}`);
console.log(`Version ${version()}`);
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) => {
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');
})
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 { createReadStream } from 'fs';
import { join } from 'path'
import { __dirname } from '../utils.js'
import { once } from 'node:events';

const read = async () => {
// Write your code here
};
const file = join(__dirname, 'streams', 'files', 'fileToRead.txt');
const readStream = createReadStream(file, 'utf-8');

readStream.pipe(process.stdout);
await once(readStream, 'end');
process.stdout.write('\n');
process.stdout.end();
}

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 { pipeline, Transform } from 'stream';

const transform = async () => {
// Write your code here
};
const myTransform = new Transform({
transform(chunk, encoding, callback) {
const reverse =
chunk
.toString()
.replace(/\n/g, "")
.split('')
.reverse().join('')+'\n'
callback(null, reverse);
},
})

pipeline(process.stdin, myTransform, process.stdout, (error) => {
if (error) {
console.log(error);
} else {
console.log('Pipeline Succesfull');
}
})
}

await transform();
14 changes: 12 additions & 2 deletions src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { stdin, stdout } from 'process';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { __dirname } from '../utils.js';

const write = async () => {
// Write your code here
};
const outputFile = createWriteStream(
join(__dirname, 'streams', 'files', 'fileToWrite.txt')
)
stdout.write('Write something:\n');
stdin.pipe(outputFile);

}

await write();
6 changes: 6 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { dirname } from 'path';
import { fileURLToPath } from 'url';

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

33 changes: 31 additions & 2 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
import { cpus } from 'os';
import { __dirname } from '../utils.js';
import { join } from 'path';
import { Worker } from 'worker_threads';

const performCalculations = async () => {
// Write your code here
};
const cpuNumbers = cpus();
let number = 10;

const workerPromises = await Promise.allSettled(
cpuNumbers.map(() => {
return new Promise((resolve, reject) => {
const worker = new Worker(join(__dirname, 'wt', 'worker.js'), {
workerData: number++,
})

worker.once('message', (msg) => resolve(msg));
worker.once('error', (err) => reject(err));
})
})
)

const results = workerPromises.map(({ status, value }) => {
return {
status: status === 'fulfilled' ? 'resolved' : 'error',
data: status === 'fulfilled' ? value : null,
}
})

console.log(results);
return results;
}

await performCalculations();
12 changes: 7 additions & 5 deletions src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// 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
};
parentPort.postMessage(nthFibonacci(workerData));
}

sendResult();
sendResult();
Loading