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

Nodejs basics sukhrob #530

Open
wants to merge 2 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
15 changes: 13 additions & 2 deletions src/cli/args.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
const parseArgs = () => {
// Write your code here
const args = process.argv.slice(2);
const output = [];

for (let i = 0; i < args.length; i += 2) {
if (args[i].startsWith("--") && args[i + 1]) {
const key = args[i].slice(2);
const value = args[i + 1];
output.push(`${key} is ${value}`);
}
}

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

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 rssVars = Object.keys(process.env)
.filter(key => key.startsWith('RSS_'))
.map(key => `${key}=${process.env[key]}`)
.join('; ');

console.log(rssVars);
};

parseEnv();
parseEnv();
13 changes: 10 additions & 3 deletions src/cp/cp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { spawn } from 'child_process';

const spawnChildProcess = async (args) => {
// Write your code here
const child = spawn('node', ['files/script.js', ...args], {
stdio: ['pipe', 'pipe', 'inherit'], // Setting up IPC
});

process.stdin.pipe(child.stdin);

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

// Put your arguments in function call to test this functionality
spawnChildProcess( /* [someArgument1, someArgument2, ...] */);
spawnChildProcess(['arg1', 'arg2']);
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 fs from "fs/promises";
import path from "path";

const copy = async () => {
// Write your code here
const source = path.join(process.cwd(), "files");
const dest = path.join(process.cwd(), "files_copy");

const sourceExist = await fs
.access(source)
.then(() => true)
.catch(() => false);
if (!sourceExist) {
throw new Error("FS operation failed"); // Source foolder doesnt exist
}

const destExist = await fs
.access(dest)
.then(() => true)
.catch(() => false);
if (destExist) {
throw new Error("FS operation failed"); // destination folder already exists
}

await fs.mkdir(dest);

const files = await fs.readdir(source);

// copy all files from source to dest.
for (const file of files) {
const srcFile = path.join(source, file);
const destFile = path.join(dest, file);
await fs.copyFile(srcFile, destFile);
}
};

await copy();
17 changes: 15 additions & 2 deletions src/fs/create.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import fs from "fs/promises";
import path from "path";

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

const fileExists = await fs
.access(filePath)
.then(() => true)
.catch(() => false);

if (fileExists) {
throw new Error("FS operation failed");
}
await fs.writeFile(filePath, "I am fresh and young", { encoding: "utf8" });
};

await create();
await create();
18 changes: 16 additions & 2 deletions src/fs/delete.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import fs from "fs/promises";
import path from "path";

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

// at first, we need to check file exist or not
const fileExists = await fs
.access(fileToRemove)
.then(() => true)
.catch(() => false);
if (!fileExists) {
throw new Error("FS operation failed");
}

await fs.unlink(fileToRemove);
};

await remove();
await remove();
1 change: 1 addition & 0 deletions src/fs/files/fresh.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
I am fresh and young
File renamed without changes.
1 change: 1 addition & 0 deletions src/fs/files_copy/dontLookAtMe.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
What are you looking at?!
7 changes: 7 additions & 0 deletions src/fs/files_copy/fileToRead.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
My content
should
be
printed
into
console
!
File renamed without changes.
1 change: 1 addition & 0 deletions src/fs/files_copy/fresh.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
I am fresh and young
1 change: 1 addition & 0 deletions src/fs/files_copy/hello.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello Node.js
3 changes: 3 additions & 0 deletions src/fs/files_copy/wrongFilename.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# This is a file with a wrong filename

Hello from **markdown**!
25 changes: 23 additions & 2 deletions src/fs/list.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
import fs from "fs/promises";
import path from "path";

const list = async () => {
// Write your code here
const dirPath = path.join(process.cwd(), "files");

const dirExist = await fs
.access(dirPath)
.then(() => true)
.catch(() => false);

if (!dirExist) {
throw new Error("FS operation failed");
}

const files = await fs.readdir(dirPath);
// print files as an array
console.log(files);

// filnames from array of files
files.forEach((file) => {
console.log(file);
});
};

await list();
await list();
20 changes: 18 additions & 2 deletions src/fs/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import fs from "fs/promises";
import path from "path";

const read = async () => {
// Write your code here
const dir = path.join(process.cwd(), "files", "fileToRead.txt");

// check file status, there or not
const fileExist = await fs
.access(dir)
.then(() => true)
.catch(() => false);
if (!fileExist) {
throw new Error("FS operation failed");
}

// read the file content in utf-8 format
const content = await fs.readFile(dir, "utf-8");
console.log(content);
};

await read();
await read();
31 changes: 29 additions & 2 deletions src/fs/rename.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
import fs from "fs/promises";
import path from "path";

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

// checking oold file exits or not
// checking new file exits already
const oldFileExist = await fs
.access(oldFile)
.then(() => true)
.catch(() => false);
if (!oldFileExist) {
throw new Error("FS operation failed(source file doesn't exist)");
}
const newFileExist = await fs
.access(newFile)
.then(() => true)
.catch(() => false);

if (newFileExist) {
throw new Error("FS operation failed(dest file already exist)");
}
if (!oldFileExist || newFileExist) {
throw new Error("FS operation failed");
}

await fs.rename(oldFile, newFile);
};

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

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

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

fileStream.on('end', () => {
const fileHash = hash.digest('hex');
console.log(`SHA256 Hash: ${fileHash}`);
});

fileStream.on('error', (err) => {
console.error('Error occurred:', err);
});
};

await calculateHash();
21 changes: 9 additions & 12 deletions src/modules/cjsToEsm.cjs → src/modules/esm.mjs
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
const path = require('path');
const { release, version } = require('os');
const { createServer: createServerHttp } = require('http');
require('./files/c');
import path from 'path';
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) {
unknownObject = require('./files/a.json');
unknownObject = await import('./files/a.json');
} else {
unknownObject = require('./files/b.json');
unknownObject = await import('./files/b.json');
}

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}`);
console.log(`Path to current file is ${import.meta.url}`);
console.log(`Path to current directory is ${path.dirname(import.meta.url)}`);

const myServer = createServerHttp((_, res) => {
res.end('Request accepted');
Expand All @@ -33,8 +31,7 @@ myServer.listen(PORT, () => {
console.log('To terminate it, use Ctrl+C combination');
});

module.exports = {
export {
unknownObject,
myServer,
};

1 change: 1 addition & 0 deletions src/streams/files/fileToWrite.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
this is written by steam api
15 changes: 13 additions & 2 deletions src/streams/read.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { createReadStream } from 'fs';
import path from 'path';

const read = async () => {
// Write your code here
const filePath = path.join('files', 'fileToRead.txt');
const fileStream = createReadStream(filePath);
// get chunk from datafile and write it
fileStream.on('data', (chunk) => {
process.stdout.write(chunk);
});
fileStream.on('error', (err) => {
console.error('Error occurred:', err);
});
};

await read();
await read();
17 changes: 15 additions & 2 deletions src/streams/transform.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { Transform } from 'stream';

const transform = async () => {
// Write your code here
const reverseStream = new Transform({
transform(chunk, encoding, callback) {
// Reverse the chunk of text
callback(null, chunk.toString().split('').reverse().join(''));
}
});

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

await transform();
await transform();

// THIS IS A COUSE FROM RS APP

// PPA SR MORF ESUOC A SI SIHT
18 changes: 16 additions & 2 deletions src/streams/write.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { createWriteStream } from 'fs';
import path from 'path';

const write = async () => {
// Write your code here
const filePath = path.join('files', 'fileToWrite.txt');
const fileStream = createWriteStream(filePath);

process.stdin.pipe(fileStream);

// fileStream.on('error', (err) => {
// console.error('Error occurred:', err);
// });

// fileStream.on('finish', () => {
// console.log('Data has been written to fileToWrite.txt');
// });
};

await write();
await write();
Loading