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.js basics #542

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
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.

14 changes: 13 additions & 1 deletion 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 arrTransformArgs = args.reduce((acc, val, index, array) => {
if (val.startsWith("--")) {
const field = val.slice(2)
const value = array[index + 1];
const resultStr = `${field} is ${value}`
acc.push(resultStr);
}
return acc
}, [])

console.log(arrTransformArgs.join(", "));
};

parseArgs();
16 changes: 15 additions & 1 deletion src/cli/env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { access } from 'fs/promises';
import path from "path";

const parseEnv = () => {
// Write your code here
const envVars = process.env;

const envVarsArray = []

for (const field in envVars) {
if (field.startsWith('RSS_')) {
const envStr = `${field}=${envVars[field]}`
envVarsArray.push(envStr);
}
}

console.log(envVarsArray.join('; '));
};

parseEnv();
22 changes: 20 additions & 2 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
import { spawn } from'child_process';
import path from "path";

const spawnChildProcess = async (args) => {
// Write your code here
const pathToScript = path.join(process.cwd(), 'src/cp/files/script.js');

const child = spawn('node', [pathToScript, ...args], {
stdio: ['pipe', 'pipe', 'inherit']
});

child.on('error', (error) => {
reject(`Failed to start child process: ${error.message}`);
});

process.stdin.pipe(child.stdin);
child.stdout.pipe(process.stdout);

child.on('exit', (code) => {
resolve(`Child process exited with code ${code}`);
});
};

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess(['someArgument1', 'someArgument2']);
23 changes: 22 additions & 1 deletion src/fs/copy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import { access, cp, mkdir, readdir, copyFile } from 'fs/promises';
import path from "path";

const copy = async () => {
// Write your code here
const sourceDir = path.join(process.cwd(), 'src/fs/files');
const destDir = path.join(process.cwd(), 'src/fs/files_copy');

try {
await access(sourceDir);
} catch (error) {
throw new Error('FS operation failed');
}

try {
await access(destDir);
throw new Error('FS operation failed');
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}

cp(sourceDir, destDir, {recursive: true});
};

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 { access, writeFile } from 'fs/promises';
import path from "path";

const create = async () => {
// Write your code here
const filePath = path.join(process.cwd(), 'src/fs/files', 'fresh.txt');

try {
await access(filePath);
throw new Error('FS operation failed');
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}

await writeFile(filePath, 'I am fresh and young', 'utf8');
};

await create();
13 changes: 12 additions & 1 deletion src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { access, unlink } from 'fs/promises';
import path from "path";

const remove = async () => {
// Write your code here
const filePath = path.join(process.cwd(), 'src/fs/files/fileToRemove.txt');

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

await unlink(filePath);
};

await remove();
10 changes: 3 additions & 7 deletions src/fs/files/fileToRead.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
My content
should
be
printed
into
console
!
aaaa ffff ggg
k
oleee
5 changes: 5 additions & 0 deletions src/fs/files/fileToWrite.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
yyyyyyyyy


close

17 changes: 16 additions & 1 deletion src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { access, readdir } from 'fs/promises';
import path from "path";

const list = async () => {
// Write your code here
const folderPath = path.join(process.cwd(), 'src/fs/files');

try {
await access(folderPath);
} catch (error) {
throw new Error('FS operation failed');
}

const files = await readdir(folderPath);

files.forEach((file) => {
console.log(file);
})
};

await list();
14 changes: 13 additions & 1 deletion src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { access, readFile } from 'fs/promises';
import path from "path";

const read = async () => {
// Write your code here
const filePath = path.join(process.cwd(), 'src/fs/files/fileToRead.txt');

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

const content = await readFile(filePath, 'utf8');
console.log(content);
};

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

const rename = async () => {
// Write your code here
const oldFile = path.join(process.cwd(), 'src/fs/files/wrongFilename.txt');
const newFile = path.join(process.cwd(), 'src/fs/files/properFilename.md');

try {
await access(oldFile)
} catch (error) {
throw Error('FS operation failed');
}

try {
await access(newFile)
throw Error('FS operation failed');
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}

renameFile(oldFile, newFile);
};

await rename();
21 changes: 19 additions & 2 deletions src/hash/calcHash.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { createReadStream } from 'fs';
import path from "path";
import { createHash } from 'crypto';
import { pipeline } from 'stream';
import { promisify } from 'util';

const pipelineAsync = promisify(pipeline);

const calculateHash = async () => {
// Write your code here
const filePath = path.join(process.cwd(), 'src/hash/files/fileToCalculateHashFor.txt');
const stream = createReadStream(filePath);
const hash = createHash('sha256');

pipeline(stream, hash, (error) => {
if (!error) {
const hexHash = hash.digest('hex');
console.log(hexHash);
}
});
};

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

This file was deleted.

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

const random = Math.random();

let unknownObject;

if (random > 0.5) {
const data = await readFile(new URL('./files/a.json', import.meta.url), 'utf-8');
unknownObject = JSON.parse(data);
} else {
const data = await readFile(new URL('./files/b.json', import.meta.url), 'utf-8');
unknownObject = JSON.parse(data);
}

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

console.log(`Path to current file is ${import.meta.url}`);
console.log(`Path to current directory is ${process.cwd()}`);

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

15 changes: 14 additions & 1 deletion src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { createReadStream } from 'fs';
import path from "path";
import { pipeline } from 'stream';

const read = async () => {
// Write your code here
const filePath = path.join(process.cwd(), 'src/fs/files/fileToRead.txt');

const stream = createReadStream(filePath);

pipeline(stream, process.stdout, (error) => {
if (error) {
console.error(error.message);
}
}
)
};

await read();
Loading