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
15 changes: 14 additions & 1 deletion src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
const result = [];
for (let i = 0; i < args.length; i++) {
const token = args[i];
if (token.startsWith('--')) {
const name = token.slice(2);
const value = args[i + 1];
if (value && !value.startsWith('--')) {
result.push(`${name} is ${value}`);
i++; // skip value
}
}
}
if (result.length) 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 prefix = 'RSS_';
const result = Object.keys(process.env)
.filter((key) => key.startsWith(prefix))
.map((key) => `${key}=${process.env[key]}`)
.join('; ');
if (result) console.log(result);
};

parseEnv();
38 changes: 35 additions & 3 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,38 @@
const spawnChildProcess = async (args) => {
// Write your code here
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

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

const spawnChildProcess = async (args = []) => {
// Resolve path to the script we want to run
const scriptPath = path.join(__dirname, 'files', 'script.js');

// Ensure args is an array
const normalizedArgs = Array.isArray(args) ? args.map(String) : [];

// Spawn a new Node.js process executing the script with provided arguments
const child = spawn(process.execPath, [scriptPath, ...normalizedArgs], {
stdio: ['pipe', 'pipe', 'inherit'], // pipe stdin & stdout, inherit stderr
});

// Pipe master stdin to child stdin, and child stdout back to master stdout
process.stdin.pipe(child.stdin);
child.stdout.pipe(process.stdout);

// Optional: handle errors for visibility
child.on('error', (err) => {
console.error('Child process error:', err);
});

// Return a promise that resolves on child exit (so caller can await if desired)
return new Promise((resolve) => {
child.on('exit', (code, signal) => {
resolve({ code, signal });
});
});
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
await spawnChildProcess(['value1', '1337', '42']);
33 changes: 32 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const copy = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const srcDir = path.join(__dirname, 'files');
const destDir = path.join(__dirname, 'files_copy');

try {
// Validate source directory exists
await fs.access(srcDir);
} catch {
throw new Error('FS operation failed');
}

// Fail if destination already exists
try {
await fs.access(destDir);
// If access succeeds, destination exists
throw new Error('FS operation failed');
} catch (err) {
// If error is because it doesn't exist, proceed; else rethrow custom error already thrown
if (err?.message === 'FS operation failed') throw err; // dest exists case above
}

try {
// Use recursive copy
await fs.cp(srcDir, destDir, { recursive: true });
} catch {
throw new Error('FS operation failed');
}
};

await copy();
23 changes: 22 additions & 1 deletion src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const create = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dir = path.join(__dirname, 'files');
const filePath = path.join(dir, 'fresh.txt');
const content = 'I am fresh and young inside of the files folder';

try {
await fs.access(filePath);
throw new Error('FS operation failed');
} catch (err) {
if (err?.message === 'FS operation failed') throw err;
}

try {
await fs.writeFile(filePath, content, 'utf8');
} catch {
throw new Error('FS operation failed');
}
};

await create();
20 changes: 19 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const remove = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.join(__dirname, 'files', 'fileToRemove.txt');

try {
await fs.access(filePath);
} catch {
throw new Error('FS operation failed');
}

try {
await fs.unlink(filePath);
} catch {
throw new Error('FS operation failed');
}
};

await remove();
1 change: 0 additions & 1 deletion src/fs/files/fileToRemove.txt

This file was deleted.

3 changes: 0 additions & 3 deletions src/fs/files/wrongFilename.txt

This file was deleted.

21 changes: 20 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const list = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dir = path.join(__dirname, 'files');

try {
await fs.access(dir);
} catch {
throw new Error('FS operation failed');
}

try {
const entries = await fs.readdir(dir);
console.log(entries);
} catch {
throw new Error('FS operation failed');
}
};

await list();
21 changes: 20 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const read = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.join(__dirname, 'files', 'fileToRead.txt');

try {
await fs.access(filePath);
} catch {
throw new Error('FS operation failed');
}

try {
const data = await fs.readFile(filePath, 'utf8');
console.log(data);
} catch {
throw new Error('FS operation failed');
}
};

await read();
31 changes: 30 additions & 1 deletion src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const rename = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dir = path.join(__dirname, 'files');
const oldPath = path.join(dir, 'wrongFilename.txt');
const newPath = path.join(dir, 'properFilename.md');

// Check old exists
try {
await fs.access(oldPath);
} catch {
throw new Error('FS operation failed');
}

// Fail if new already exists
try {
await fs.access(newPath);
throw new Error('FS operation failed');
} catch (err) {
if (err?.message === 'FS operation failed') throw err;
}

try {
await fs.rename(oldPath, newPath);
} catch {
throw new Error('FS operation failed');
}
};

await rename();
42 changes: 40 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
import { createReadStream } from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

// filepath: c:\Users\Sergeyu\IdeaProjects\node-nodejs-basics\src\hash\calcHash.js
const calculateHash = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.join(__dirname, 'files', 'fileToCalculateHashFor.txt');

return new Promise((resolve, reject) => {
const hash = createHash('sha256');
const stream = createReadStream(filePath);

stream.on('error', (err) => {
console.error('Stream error while reading file:', err.message);
reject(err);
});

stream.on('data', (chunk) => {
hash.update(chunk);
});

stream.on('end', () => {
try {
const digest = hash.digest('hex');
console.log(digest);
resolve(digest);
} catch (err) {
console.error('Hash digest error:', err.message);
reject(err);
}
});
});
};

await calculateHash();
try {
await calculateHash();
} catch (err) {
// Already logged detailed error above; keep outer catch minimal
process.exitCode = 1;
}
40 changes: 40 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import path from 'node:path';
import { release, version } from 'node:os';
import { createServer as createServerHttp } from 'node:http';
import { fileURLToPath } from 'node:url';

// Load side-effect CommonJS module
import './files/c.cjs';

// Emulate __filename and __dirname in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const random = Math.random();

// Conditional JSON module import using top-level await
const unknownObject = (
await import(random > 0.5 ? './files/a.json' : './files/b.json', { assert: { type: 'json' } })
).default;

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');
});

export { unknownObject, myServer };
26 changes: 24 additions & 2 deletions src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import { createReadStream } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { pipeline } from 'node:stream';

const read = async () => {
// Write your code here
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filePath = path.join(__dirname, 'files', 'fileToRead.txt');

await new Promise((resolve, reject) => {
pipeline(createReadStream(filePath), process.stdout, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};

await read();
try {
await read();
} catch (e) {
console.error('Stream read error:', e.message);
process.exitCode = 1;
}
Loading