Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node-nodejs-basics #563

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/.idea
/node_modules
16 changes: 16 additions & 0 deletions package-lock.json

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

16 changes: 14 additions & 2 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
let currentIndex;
const args = process.argv.filter((arg, index) => {
if (arg.startsWith('--')) {
currentIndex = index;
return true;
}
return index === currentIndex + 1;
})
for (let i = 0; i < args.length; i += 2) {
const propName = args[i].replace('--', '');
const value = args[i + 1];
console.log(`${propName} is ${value}`);
}
};

parseArgs();
parseArgs();
9 changes: 7 additions & 2 deletions 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 processEnv = process.env
const env = Object.keys(processEnv)
.filter((val) => val.startsWith('RSS_')).map((key) => {
return `${key}=${processEnv[key]}`
}).join('; ');
console.log(env);
};

parseEnv();
parseEnv();
16 changes: 14 additions & 2 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';

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

const spawnChildProcess = async (args) => {
// Write your code here
const pathToScript = path.join(__dirname, 'files', 'script.js');
const spawnProcessScript = spawn('node', [pathToScript, ...args], {
stdio: ['pipe', 'pipe', 'pipe', 'ipc']
});
process.stdin.pipe(spawnProcessScript.stdin)
spawnProcessScript.stdout.pipe(process.stdout)
};

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

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

if (!fs.existsSync(currentFilePath)) {
throw new Error('FS operation failed')
}

if (fs.existsSync(copyFilePath)) {
throw new Error('FS operation failed')
}

fs.mkdirSync(copyFilePath);

const recursiveCopy = (fromPath, toPath) => {
fs.readdirSync(currentFilePath, {withFileTypes: true}).forEach((paths) => {
const currentFilePath = path.join(fromPath, paths.name);
const copyFilePath = path.join(toPath, paths.name);

if (paths.isDirectory()) {
fs.mkdirSync(currentFilePath);
recursiveCopy(currentFilePath,copyFilePath)
} else {
fs.copyFileSync(currentFilePath,copyFilePath)
}
})
}

recursiveCopy(currentFilePath, copyFilePath)

};

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const create = async () => {
// Write your code here
const freshPath = path.join(__dirname, 'files', 'fresh.txt');
fs.access(freshPath, fs.constants.F_OK, (err) => {
if (!err) {
throw new Error('FS operation failed')
}
fs.writeFile(freshPath, 'I am fresh and young', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File was been created!');
});
});
};

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

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

const remove = async () => {
// Write your code here
const removeFilePath = path.join(__dirname, 'files', 'fileToRemove.txt');

try {
await fs.access(removeFilePath);
await fs.unlink(removeFilePath);
} catch (err) {
if (err.code === 'ENOENT') {
console.error('FS operation failed');
throw new Error('FS operation failed');
} else {
throw err;
}
}
};

await remove();
await remove();
26 changes: 24 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
import fs from 'node:fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

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

const list = async () => {
// Write your code here
const projectFiles = path.join(__dirname, 'files');

try {
await fs.access(projectFiles);
const files = await fs.readdir(projectFiles);
files.forEach(file => {
console.log(file);
});
} catch (err) {
if (err.code === 'ENOENT') {
console.error('FS operation failed')
throw new Error('FS operation failed');
} else {
throw err;
}
}
};

await list();
await list();
25 changes: 23 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import fs from 'node:fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';


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

const read = async () => {
// Write your code here
const readPath = path.join(__dirname, 'files', 'fileToRead.txt');

try {
await fs.access(readPath);
const content = await fs.readFile(readPath, 'utf-8');
console.log(content);
} catch (err) {
if (err.code === 'ENOENT') {
console.error('FS operation failed');
throw new Error('FS operation failed');
} else {
throw err;
}
}
};

await read();
await read();
34 changes: 32 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
import fs from 'node:fs/promises';
import path from "path";
import { fileURLToPath } from 'url';

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

const rename = async () => {
// Write your code here
const currentPath = path.join(__dirname, 'files', 'wrongFilename.txt');
const newPath = path.join(__dirname, 'files', 'properFilename.md');

try {
await fs.access(currentPath);
await fs.access(newPath).then(() => {
console.error('FS operation failed')
throw new Error('FS operation failed');
}).catch(async (err) => {
if (err.code === 'ENOENT') {
await fs.rename(currentPath, newPath);
} else {
throw err;
}
})

} catch (err) {
if (err.code === 'ENOENT') {
console.error('FS operation failed');
throw new Error('FS operation failed');
} else {
throw err;
}
}
};

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const calculateHash = async () => {
// Write your code here
const pathToFile = path.join(__dirname, 'files', 'fileToCalculateHashFor.txt');
const readSteamFile = createReadStream(pathToFile);

readSteamFile.on('data', (chunk) => {
createHash('sha256').update(chunk);
});

readSteamFile.on('end', () => {
console.log(createHash('sha256').digest('hex'));
});
};

await calculateHash();
await calculateHash();
40 changes: 0 additions & 40 deletions src/modules/cjsToEsm.cjs

This file was deleted.

51 changes: 51 additions & 0 deletions src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import path from 'path';
import fs from 'node:fs/promises';
import { release, version } from 'os';
import { createServer as createServerHttp } from 'http';
import './files/c.js';
import { fileURLToPath } from 'url';

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

const getDataFromJson = async (path) => {
const data = await fs.readFile(path, 'utf-8');
return JSON.parse(data);
};

const firstJson = await getDataFromJson(path.join(__dirname, 'files/a.json'));
const secondJson = await getDataFromJson(path.join(__dirname, 'files/b.json'));


const random = Math.random();

let unknownObject;

if (random > 0.5) {
unknownObject = firstJson;
} else {
unknownObject = secondJson;
}

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

Loading