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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
.idea/
package-lock.json
11 changes: 10 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,14 @@
"bugs": {
"url": "https://github.com/AlreadyBored/node-nodejs-basics/issues"
},
"homepage": "https://github.com/AlreadyBored/node-nodejs-basics#readme"
"homepage": "https://github.com/AlreadyBored/node-nodejs-basics#readme",
"dependencies": {
"crypto": "^1.0.1",
"fs": "^0.0.1-security",
"http": "^0.0.1-security",
"os": "^0.1.2",
"path": "^0.12.7",
"stream": "^0.0.2",
"zlib": "^1.0.5"
}
}
10 changes: 8 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
const parseArgs = () => {
// Write your code here
};
const result = [];
const agrsResult = process.argv;
agrsResult.splice(0,2);
for (let i = 0; i < agrsResult.length; i += 2) {
result.push(`${agrsResult[i]} is ${agrsResult[i + 1]}`)
}
console.log(result.join(', '))
}

parseArgs();
7 changes: 6 additions & 1 deletion 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 rssKeys = Object.keys(process.env).filter((key) => key.match(/^RSS_/gm));
const result = [];
for (let rssKey of rssKeys) {
result.push(`${rssKey}=${process.env[rssKey]}`);
}
console.log(result.join('; '));
};

parseEnv();
7 changes: 5 additions & 2 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import cp from 'child_process';

const spawnChildProcess = async (args) => {
// Write your code here
const child = cp.spawn('node', ['src/cp/files/script.js', ...args], {stdio: 'inherit'});
child.on('error', (err) => console.log(err));
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess(['--example', '--example2']);
9 changes: 8 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import * as fs from 'fs';

const errorMessage = 'FS operation failed';

const copy = async () => {
// Write your code here
await fs.promises.access('src/fs/files_copy')
.then(() => console.log(errorMessage))
.catch(async() => await fs.promises.cp('src/fs/files', 'src/fs/files_copy', { errorOnExist: true, recursive: true}))
.catch(() => console.log(errorMessage))
};

await copy();
6 changes: 5 additions & 1 deletion src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import * as fs from 'fs';

const create = async () => {
// Write your code here
await fs.promises.writeFile('src/fs/files/fresh.txt', 'I am fresh and young', {flag: 'ax'}).catch((err) => {
console.log('FS operation failed');
});
};

await create();
6 changes: 5 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import * as fs from 'fs';

const errorMessage = 'FS operation failed';

const remove = async () => {
// Write your code here
await fs.promises.rm('src/fs/files/fileToRemove.txt').catch(() => console.log(errorMessage));
};

await remove();
10 changes: 9 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import * as fs from 'fs';

const errorMessage = 'FS operation failed';

const list = async () => {
// Write your code here
await fs.promises.readdir('src/fs/files').then((files) => {
for (let file of files) {
console.log(file);
}
}).catch(() => console.log(errorMessage));
};

await list();
10 changes: 8 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
const read = async () => {
// Write your code here
import * as fs from 'fs';

const errorMessage = 'FS operation failed';

const read = async () => {0
await fs.promises.readFile('src/fs/files/fileToRead.txt', {encoding: 'utf8'})
.then((data) => console.log(data))
.catch(() => console.log(errorMessage));
};

await read();
10 changes: 9 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import * as fs from 'fs';

const errorMessage = 'FS operation failed';

const rename = async () => {
// Write your code here
await fs.promises.access('src/fs/files/wrongFilename.txt').then(async () => {
return await fs.promises.access('src/fs/files/properFilename.md')
.then(() => console.log(errorMessage))
.catch(async () => await fs.promises.rename('src/fs/files/wrongFilename.txt', 'src/fs/files/properFilename.md'))
}).catch(() => console.log(errorMessage));
};

await rename();
14 changes: 13 additions & 1 deletion src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { createHash } from "crypto";
import * as fs from 'fs';


const calculateHash = async () => {
// Write your code here
const hash = createHash("sha256");
const readStream = fs.createReadStream('src/hash/files/fileToCalculateHashFor.txt');
readStream.on('data', (chunk) => {
hash.update(chunk);
});
readStream.on('end', () => {
console.log(hash.digest("hex"));
})

};

await calculateHash();
28 changes: 14 additions & 14 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
const path = require('path');
const { release, version } = require('os');
const { createServer: createServerHttp } = require('http');
require('./files/c');
import path from 'path';
import { fileURLToPath } from 'url';
import { release, version } from 'os';
import { createServer as createServerHttp } from 'http';
import('./files/c.js');
import aFile from "./files/a.json" assert { type: "json" };
import bFile from "./files/b.json" assert { type: "json" };


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

let unknownObject;
export let unknownObject;

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

console.log(`Release ${release()}`);
Expand All @@ -20,7 +26,7 @@ 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) => {
export const myServer = createServerHttp((_, res) => {
res.end('Request accepted');
});

Expand All @@ -32,9 +38,3 @@ myServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
console.log('To terminate it, use Ctrl+C combination');
});

module.exports = {
unknownObject,
myServer,
};

7 changes: 6 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import * as fs from 'fs';

const read = async () => {
// Write your code here
const readableStream = fs.createReadStream('src/streams/files/fileToRead.txt');
readableStream.on('data', (chunk) => {
process.stdout.write(chunk.toString());
})
};

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 "stream";

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

const reverse = new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().split('').reverse().join(''));
},
});

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

await transform();
8 changes: 7 additions & 1 deletion src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import * as fs from 'fs';

const write = async () => {
// Write your code here
const writableStream = fs.createWriteStream('src/streams/files/fileToWrite.txt');

process.stdin.on('data', data => {
writableStream.write(data.toString());
});
};

await write();
38 changes: 37 additions & 1 deletion src/wt/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,41 @@
import os from 'os';
import { Worker } from 'worker_threads';
import path from 'path';

const numberOfWorkers = os.cpus().length;
const fullPath = path.resolve('src/wt/worker.js');

function createPromise(workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker(fullPath, { workerData });
worker.on('message', resolve);
worker.on('error', reject);
});
}

const performCalculations = async () => {
// Write your code here
const array = [];

for (let i = 0; i < numberOfWorkers; i++) {
array.push(createPromise(10 + i));
}

await Promise.allSettled(array).then((results) => {
const consoleResponse = results.map((result) => {
if (result.status === 'fulfilled') {
return {
status: 'resolved',
data: result.value
};
} else if (result.status === 'rejected') {
return {
status: 'error',
data: null
};
}
});
console.log(consoleResponse);
});
};

await performCalculations();
4 changes: 3 additions & 1 deletion src/wt/worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { workerData, parentPort } from 'worker_threads';

// n should be received from main thread
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();
9 changes: 8 additions & 1 deletion src/zip/compress.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import {createGzip} from 'zlib';
import * as fs from 'fs';

const compress = async () => {
// Write your code here
const gzip = createGzip();
const readableStream = fs.createReadStream('src/zip/files/fileToCompress.txt');
const writableStream = fs.createWriteStream('src/zip/files/archive.gz');

readableStream.pipe(gzip).pipe(writableStream);
};

await compress();
9 changes: 8 additions & 1 deletion src/zip/decompress.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import {createGunzip} from 'zlib';
import * as fs from 'fs';

const decompress = async () => {
// Write your code here
const gunzip = createGunzip();
const readableStream = fs.createReadStream('src/zip/files/archive.gz');
const writableStream = fs.createWriteStream('src/zip/files/fileToCompress.txt');

readableStream.pipe(gunzip).pipe(writableStream);
};

await decompress();