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: 8 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
const parseArgs = () => {
// Write your code here
const argLine = process.argv.slice(2).join(' ');
const propValueRegexp = /(--[\w|-]+) (\w+)/gm
const pairs = argLine.match(propValueRegexp)
.map((pair)=>{
console.log(pair);
return pair.replace('--', '').replace(' ', ' is ');
});
console.log(pairs.join(', '));
};

parseArgs();
11 changes: 10 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
const parseEnv = () => {
// Write your code here
const env = process.env || {};
const rssVars = Object.entries(env)
.filter(([key,]) => key.startsWith('RSS_'))
.map(([key, value]) => {
if (key.startsWith('RSS_')) {
return `${key}=${value}`
}
})
.join('; ');
console.log(rssVars);
};

parseEnv();
11 changes: 10 additions & 1 deletion src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { fork } from "node:child_process"
import * as path from 'path';
import { fileURLToPath } from 'url';

const spawnChildProcess = async (args) => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const scriptPath = path.resolve(dirName, 'files/script.js');

const childProcess = fork(scriptPath, args, { stdio: 'pipe' });
process.stdin.pipe(childProcess.stdin);
childProcess.stdout.pipe(process.stdout);
};

// Put your arguments in function call to test this functionality
Expand Down
17 changes: 16 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { cp } from 'node:fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import throwFSError from './utils/FSError.js';

const copy = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/');
const destName = path.resolve(dirName, 'files-copy/');

// experimental but whatever
cp(srcName, destName, { recursive: true, errorOnExist: true, force: false }, (err) => {
if (err) {
throwFSError();
}
console.log("The direcroty has been copied!")
});
};

await copy();
16 changes: 15 additions & 1 deletion src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { writeFile } from 'node:fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import throwFSError from './utils/FSError.js';

const create = async () => {
// Write your code here
const data = 'I am fresh and young';
const dirName = path.dirname(fileURLToPath(import.meta.url));
const fileName = path.resolve(dirName, 'files/fresh.txt');

writeFile(fileName, data, { flag: 'wx' }, (err) => {
if (err) {
throwFSError();
}
console.log('The file has been saved!');
});
};

await create();
17 changes: 16 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import * as path from 'path';
import { fileURLToPath } from 'url';
import throwFSError from './utils/FSError.js';
import { unlink } from 'node:fs';

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

unlink(srcName, (err) => {
if (err /*&& err.code == 'ENOENT'*/) {
throwFSError();
} else {
console.log("The file has been deleted!")
}
});

};

await remove();
14 changes: 13 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import * as path from 'path';
import { fileURLToPath } from 'url';
import throwFSError from './utils/FSError.js';
import { readdir } from 'node:fs';

const list = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/');
readdir(srcName, (err, files)=>{
if(err){
throwFSError();
}
console.log(files.join(', '));
})
};

await list();
15 changes: 14 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import * as path from 'path';
import { fileURLToPath } from 'url';
import throwFSError from './utils/FSError.js';
import { readFile } from 'node:fs';

const read = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/fileToRead.txt');

readFile(srcName, 'utf8', (err, data) => {
if (err){
throwFSError();
};
console.log(data);
});
};

await read();
26 changes: 25 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
import * as path from 'path';
import { fileURLToPath } from 'url';
import throwFSError from './utils/FSError.js';
import { stat, rename as fs_raname } from 'node:fs/promises';

const rename = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/wrongFilename.txt');
const destName = path.resolve(dirName, 'files/properFilename.md');

Promise.allSettled([
stat(srcName),
stat(destName),
])
.then(([src, dest]) => {
if (src.status !== 'fulfilled' || !src.value.isFile() || dest.status !== 'rejected') {
throwFSError();
}
fs_raname(srcName, destName);
})
.then(() => {
console.log("The file has been renamed!")
})
.catch((err) => {
console.error(err);
})
};

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

export default function throwFSError() {
throw new Error('FS operation failed');
}
23 changes: 22 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import * as path from 'path';
import { fileURLToPath } from 'url';
import { readFile } from 'node:fs';

const calculateHash = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/fileToCalculateHashFor.txt');

const {
createHash,
} = await import('node:crypto');
const hash = createHash('sha256');



readFile(srcName, 'utf8', (err, data) => {
if (err) {
throw err;
};
console.log(data);
hash.update(data);
console.log(hash.digest('hex'));
});
};

await calculateHash();
48 changes: 48 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import path from 'path';
import * as url from 'url';
import { release, version } from 'node:os';
import * as http from 'http'
import { readFile } from 'fs/promises';

const getJSON = async function(path){
return JSON.parse(
await readFile(
new URL(path, import.meta.url)
)
)};

const bFile = await getJSON('./files/b.json');
const aFile = await getJSON('./files/a.json');

const random = Math.random();

export let unknownObject;

if (random > 0.5) {
unknownObject = aFile;
} else {
unknownObject = bFile;
}

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

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = url.fileURLToPath(new URL('.', import.meta.url));

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

export const myServer = http.createServer((_, 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');
});
24 changes: 23 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import {createReadStream} from "node:fs"
import * as path from 'path';
import { fileURLToPath } from 'url';

const read = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/fileToRead.txt');

const readerStream = createReadStream(srcName);
readerStream.setEncoding('UTF8');

readerStream.on('data', ((chunk) => {
process.stdout.write(chunk);
}));

readerStream.on('end', (() => {
console.log('');
console.log('File reading complete.');
}));

readerStream.on('error', ((err) => {
console.log(err);
}));

};

await read();
11 changes: 10 additions & 1 deletion src/streams/transform.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { Transform } from 'node:stream';


const transform = async () => {
// Write your code here
const transformStream = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().split("").reverse().join(""));
callback();
}
});
process.stdin.pipe(transformStream).pipe(process.stdout);
};

await transform();
18 changes: 17 additions & 1 deletion src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { createWriteStream } from "node:fs"
import * as path from 'path';
import { fileURLToPath } from 'url';

const write = async () => {
// Write your code here
const dirName = path.dirname(fileURLToPath(import.meta.url));
const srcName = path.resolve(dirName, 'files/fileToWrite.txt');

const writerStream = createWriteStream(srcName);

console.log('Write something to file. Press CTRL+C to exit');

process.stdin.pipe(writerStream);

writerStream.on('error', (error) => {
console.error('Error writing to file:', error);
writerStream.end();
});
};

await write();
44 changes: 42 additions & 2 deletions src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
import { Worker } from "node:worker_threads"
import { cpus } from "node:os"
import * as path from 'path';
import { fileURLToPath } from 'url';

const performCalculations = async () => {
// Write your code here
};
const dirName = path.dirname(fileURLToPath(import.meta.url));
const workerPath = path.resolve(dirName, 'worker.js');
const systemCpus = cpus();

function createWorkerThread(workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker(workerPath, { workerData });

worker.on('message', (value)=>{
resolve({status: 'resolved', data: value})
});
worker.on('error', (err)=>{
resolve({status: 'error', data: null})
});
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
});
};

const workerPromises = [];
const initialN = 10;

for (let i = 0; i < systemCpus.length; i++) {
workerPromises.push(createWorkerThread({ n: initialN + i }));
}

Promise.allSettled(workerPromises)
.then((results) => {
console.log('Fibonacci results:', results.map(item=>item.value));
})
.catch((error) => {
console.error('Error:', error);
});
}

await performCalculations();
Loading