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
/node_modules
.env
36 changes: 36 additions & 0 deletions package-lock.json

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

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,7 @@
"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": {
}
}
12 changes: 12 additions & 0 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
const parsedArguments = {};

for (let i = 0; i < args.length; i += 2) {
const propName = args[i].replace(/^--/, '');
const propValue = args[i + 1];
parsedArguments[propName] = propValue;
}

for (const [propName, propValue] of Object.entries(parsedArguments)) {
console.log(`${propName} is ${propValue}`);
}
};

parseArgs();
57 changes: 56 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,60 @@
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourceFilePath = path.join(__dirname, '.env');

const getRootPath = () => {
let currentPath = __dirname;

// Navigate up until reaching the root directory
while (!fs.existsSync(path.join(currentPath, '.env'))) {
currentPath = path.dirname(currentPath);

// Check if we have reached the root
if (currentPath === path.dirname(currentPath)) {
throw new Error('Unable to find the root directory.');
}
}

console.log(currentPath);
return currentPath;
}

const parseEnv = () => {
// Write your code here
try {
const prefix = "RSS_";
const envFilePath = path.join(getRootPath(), '.env');
const envFileContent = fs.readFileSync(envFilePath, 'utf8');

const envVariables = envFileContent.split('\n').filter(line => line.trim() !== '');

envVariables.forEach(variable => {
const [key, value] = variable.split('=');
process.env[key] = value;
});

const allVariables = process.env;
const filteredVariables = Object.keys(allVariables)
.filter((key) => key.startsWith(prefix))
.reduce((obj, key) => {
obj[key] = allVariables[key];
return obj;
}, {});

const formattedVariables = Object.entries(filteredVariables)
.map(([key, value]) => `${key}=${value}`)
.join("; ");

console.log(`Environment variables with prefix "${prefix}":`);
console.log(formattedVariables);

} catch (err) {
console.log(err);
}
};

parseEnv();
45 changes: 44 additions & 1 deletion src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,49 @@
import { spawn } from "child_process";
import { fileURLToPath } from 'url';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourceFilePath = path.join(__dirname, 'files', 'script.js');

const spawnChildProcess = async (args) => {
// Write your code here
return new Promise((resolve, reject) => {
const child = spawn(sourceFilePath, args, { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] });

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

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

child.on('message', (message) => {e
resolve(message);
});

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

child.on('close', (code) => {
if (code === 0) {
resolve(code);
} else {
reject(code);
}
});
});
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess( ["someArgument1", "someArgument2"])
.then((result) => {
console.log('Process completed successfully');
console.log('Exit code:', result);
})
.catch((error) => {
console.error('Error during process execution');
console.error('Exit code:', error);
});
31 changes: 30 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const copy = async () => {
// Write your code here
const sourceFolderPath = path.join(__dirname, 'files');
const targetFolderPath = path.join(__dirname, 'files_copy');
try {
if(!fs.existsSync(sourceFolderPath)) {
throw new Error('FS operation failed: Source folder does not exist');
}

if(fs.existsSync(targetFolderPath)) {
throw new Error('FS operation failed: Target folder already exists');
}

fs.mkdirSync(targetFolderPath);
const files = fs.readdirSync(sourceFolderPath);

files.forEach(file => {
const sourceFilePath = path.join(sourceFolderPath, file);
const targetFilePath = path.join(targetFolderPath, file);
fs.copyFileSync(sourceFilePath, targetFilePath);
});
console.log('Files copied successfully');
}
catch (error) {
console.error(error.message);
}
};

await copy();
26 changes: 24 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const filePath = path.join(__dirname, 'fresh.txt');

const msg = 'I am fresh and young';
const create = async () => {
// Write your code here
try {
if (fs.existsSync(filePath)) {
throw new Error('FS operation failed: File already exists');
}

fs.writeFile(filePath, msg, (err) => {
if (err) throw err;
});

console.log('File created successfully: fresh.txt');
} catch (error) {
console.error(error.message);
}
};

await create();
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 { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const sourceFilePath = path.join(__dirname, 'files', 'fileToRemove.txt');

const remove = async () => {
// Write your code here
try {
if(!fs.existsSync(sourceFilePath)) {
throw new Error('FS operation failed: Source file does not exist');
}
fs.unlinkSync(sourceFilePath);
console.log('File removed successfully');
} catch (error) {
console.error(error.message);
}
};

await remove();
22 changes: 21 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const sourceFolderPath = path.join(__dirname, 'files');


const list = async () => {
// Write your code here
try {
if(!fs.existsSync(sourceFolderPath)) {
throw new Error('FS operation failed: Source folder does not exist');
}

const files = fs.readdirSync(sourceFolderPath);
console.log('Filenames in the "files" folder:');
files.forEach(file => {
console.log(file);
});
} catch (error) {
console.error(error.message);
}
};

await list();
19 changes: 18 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourceFilePath = path.join(__dirname, 'files', 'fileToRead.txt');

const read = async () => {
// Write your code here
try {
if(!fs.existsSync(sourceFilePath)) {
throw new Error('FS operation failed: Source file does not exist');
}
const fileContent = fs.readFileSync(sourceFilePath, 'utf-8');
console.log('File content:');
console.log(fileContent);
} catch (error) {
console.error(error.message);
}
};

await read();
25 changes: 24 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourceFilePath = path.join(__dirname, 'files', 'wrongFilename.txt');
const targetFilePath = path.join(__dirname, 'files', 'properFilename.md');

const rename = async () => {
// Write your code here
try {
if(!fs.existsSync(sourceFilePath)) {
throw new Error('FS operation failed: Source file does not exist');
}

if(fs.existsSync(targetFilePath)) {
throw new Error('FS operation failed: Target file already exists');
}

fs.renameSync(sourceFilePath, targetFilePath);
console.log('File renamed successfully');
}
catch (error) {
console.error(error.message);
}
};

await rename();
23 changes: 23 additions & 0 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
import fs from 'fs';
import crypto from 'crypto';
import { fileURLToPath } from 'url';
import path from 'path';
import { TextEncoder } from 'util';

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

const calculateHash = async () => {
// Write your code here
try {
const sourceFilePath = path.join(__dirname, 'files', 'fileToCalculateHashFor.txt');

const fileData = fs.createReadStream(sourceFilePath);
const buffer = new TextEncoder().encode(fileData);

const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');

console.log(`SHA256 Hash for ${sourceFilePath}: ${hashHex}`);
} catch (error) {
console.error(error.message);
}
};

await calculateHash();
Loading