diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..27c2b2d5fe --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cSpell.words": ["asar"] +} diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000000..b9684068e3 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,7 @@ +{ + "name": "node-nodejs-basics", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000..34b7366dcf --- /dev/null +++ b/package-lock.json @@ -0,0 +1,17 @@ +{ + "name": "node-nodejs-basics", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "node-nodejs-basics", + "version": "1.0.0", + "license": "ISC", + "engines": { + "node": ">=24.10.0", + "npm": ">=10.9.2" + } + } + } +} diff --git a/src/cli/args.js b/src/cli/args.js index 9e3622f791..829a8dca99 100644 --- a/src/cli/args.js +++ b/src/cli/args.js @@ -1,5 +1,18 @@ +const PREFIX = '--' + const parseArgs = () => { - // Write your code here -}; + const formatArgumentsArr = process.argv + .slice(2) + .reduce((acc, value, index, array) => { + if (value.startsWith(PREFIX)) { + const argument = `${value.replace(PREFIX, '')} is ${array[index + 1]}` + return [...acc, argument] + } + return acc + }, []) + + const formatArgumentsStr = formatArgumentsArr.join(', ') + console.log(formatArgumentsStr) +} -parseArgs(); +parseArgs() diff --git a/src/cli/env.js b/src/cli/env.js index e3616dc8e7..a11d310339 100644 --- a/src/cli/env.js +++ b/src/cli/env.js @@ -1,5 +1,21 @@ +const PREFIX = 'RSS_' + const parseEnv = () => { - // Write your code here -}; + const envVariables = Object.entries(process.env).reduce( + (acc, value, index, array) => { + const [nameVar, valueVar] = value + + if (nameVar.startsWith(PREFIX)) { + const variable = `${nameVar}=${valueVar}` + return [...acc, variable] + } + return acc + }, + [] + ) + + const strFormatVariables = envVariables.join(', ') + console.log(strFormatVariables) +} -parseEnv(); +parseEnv() diff --git a/src/cp/cp.js b/src/cp/cp.js index 72c6addc9c..ceabe102d2 100644 --- a/src/cp/cp.js +++ b/src/cp/cp.js @@ -1,6 +1,10 @@ -const spawnChildProcess = async (args) => { - // Write your code here -}; +import path from 'node:path' +import { fork } from 'node:child_process' -// Put your arguments in function call to test this functionality -spawnChildProcess( /* [someArgument1, someArgument2, ...] */); +const pathFileFork = path.resolve(import.meta.dirname, 'files/script.js') + +const spawnChildProcess = async args => { + fork(pathFileFork, args) +} + +spawnChildProcess(['someArgument1', 'someArgument2']) diff --git a/src/cp/files/script.js b/src/cp/files/script.js index 0c6654f12f..8280ed7067 100644 --- a/src/cp/files/script.js +++ b/src/cp/files/script.js @@ -1,19 +1,19 @@ -import { EOL } from 'node:os'; -import { argv, stdout, stdin, exit } from 'node:process'; +import { EOL } from 'node:os' +import { argv, stdout, stdin, exit } from 'node:process' -const args = argv.slice(2); +const args = argv.slice(2) -console.log(`Total number of arguments is ${args.length}`); -console.log(`Arguments: ${JSON.stringify(args)}${EOL}`); +console.log(`Total number of arguments is ${args.length}`) +console.log(`Arguments: ${JSON.stringify(args)}${EOL}`) -const echoInput = (chunk) => { - const chunkStringified = chunk.toString(); +const echoInput = chunk => { + const chunkStringified = chunk.toString() - if (chunkStringified.includes('CLOSE')) { - exit(0); - } + if (chunkStringified.includes('CLOSE')) { + exit(0) + } - stdout.write(`Received from master process: ${chunk.toString()}${EOL}`); -}; + stdout.write(`Received from master process: ${chunk.toString()}${EOL}`) +} -stdin.on('data', echoInput); +stdin.on('data', echoInput) diff --git a/src/fs/copy.js b/src/fs/copy.js index e226075b4c..64feab0c9b 100644 --- a/src/fs/copy.js +++ b/src/fs/copy.js @@ -1,5 +1,24 @@ +import { cp } from 'fs/promises' +import path from 'path' +import { isFileExists } from '../../utils.js' + +const srcFolderPath = path.resolve(import.meta.dirname, 'files') +const destFolderPath = path.resolve(import.meta.dirname, 'files_copy') +const isSrcFolderPathExists = await isFileExists(srcFolderPath) + const copy = async () => { - // Write your code here -}; + if (!isSrcFolderPathExists) { + throw new Error('FS operation failed') + } else { + await cp(srcFolderPath, destFolderPath, { + recursive: true, + errorOnExist: true, + force: false, + }).catch(error => { + console.log(error) + throw new Error('FS operation failed') + }) + } +} -await copy(); +await copy() diff --git a/src/fs/create.js b/src/fs/create.js index 6ede285599..fe18b09f11 100644 --- a/src/fs/create.js +++ b/src/fs/create.js @@ -1,5 +1,15 @@ +import { writeFile } from 'fs/promises' +import path from 'path' + +const fileUrl = path.resolve(import.meta.dirname, 'files/fresh.txt') + const create = async () => { - // Write your code here -}; + try { + await writeFile(fileUrl, 'I am fresh and young', { flag: 'wx' }) + } catch (err) { + console.log(err) + throw new Error('FS operation failed') + } +} -await create(); +await create() diff --git a/src/fs/delete.js b/src/fs/delete.js index a70b13766c..55f5ca86f9 100644 --- a/src/fs/delete.js +++ b/src/fs/delete.js @@ -1,5 +1,15 @@ +import { rm } from 'fs/promises' +import path from 'path' + +const filePath = path.resolve(import.meta.dirname, 'files/fileToRemove.txt') + const remove = async () => { - // Write your code here -}; + try { + await rm(filePath) + } catch (error) { + console.log(error) + throw new Error('FS operation failed') + } +} -await remove(); +await remove() diff --git a/src/fs/files/fileToRemove.txt b/src/fs/files/fileToRemove.txt index 43e64cd45c..e69de29bb2 100644 --- a/src/fs/files/fileToRemove.txt +++ b/src/fs/files/fileToRemove.txt @@ -1 +0,0 @@ -How dare you! \ No newline at end of file diff --git a/src/fs/files/fresh.txt b/src/fs/files/fresh.txt new file mode 100644 index 0000000000..205d704cb7 --- /dev/null +++ b/src/fs/files/fresh.txt @@ -0,0 +1 @@ +I am fresh and young \ No newline at end of file diff --git a/src/fs/files/wrongFilename.txt b/src/fs/files/properFilename.md similarity index 100% rename from src/fs/files/wrongFilename.txt rename to src/fs/files/properFilename.md diff --git a/src/fs/list.js b/src/fs/list.js index 0c0fa21f7e..01e373040d 100644 --- a/src/fs/list.js +++ b/src/fs/list.js @@ -1,5 +1,16 @@ +import { readdir } from 'fs/promises' +import path from 'path' + +const folderPath = path.resolve(import.meta.dirname, 'files') + const list = async () => { - // Write your code here -}; + try { + const listFiles = await readdir(folderPath) + console.log(listFiles) + } catch (error) { + console.log(error) + throw new Error('FS operation failed') + } +} -await list(); +await list() diff --git a/src/fs/read.js b/src/fs/read.js index e3938be563..5575debdec 100644 --- a/src/fs/read.js +++ b/src/fs/read.js @@ -1,5 +1,16 @@ +import { promises as fs } from 'fs' +import path from 'path' + +const filePath = path.resolve(import.meta.dirname, 'files/fileToRead.txt') + const read = async () => { - // Write your code here -}; + try { + const fileContent = await fs.readFile(filePath, 'utf-8') + console.log(fileContent) + } catch (error) { + console.log(error) + throw new Error('FS operation failed') + } +} -await read(); +await read() diff --git a/src/fs/rename.js b/src/fs/rename.js index b1d65b0c86..b3b0f59601 100644 --- a/src/fs/rename.js +++ b/src/fs/rename.js @@ -1,5 +1,18 @@ +import { rename } from 'fs/promises' +import path from 'path' + +import { isFileExists } from '../../utils.js' + +const oldFileName = path.resolve(import.meta.dirname, 'wrongFilename.txt') +const newFileName = path.resolve(import.meta.dirname, 'properFilename.md') +const isNewFileNameExists = await isFileExists(newFileName) + const rename = async () => { - // Write your code here -}; + if (isNewFileNameExists) { + throw new Error('FS operation failed') + } else { + await rename(oldFileName, newFileName) + } +} -await rename(); +await rename() diff --git a/src/hash/calcHash.js b/src/hash/calcHash.js index e37c17ed62..e15553fc33 100644 --- a/src/hash/calcHash.js +++ b/src/hash/calcHash.js @@ -1,5 +1,16 @@ +import { readFile } from 'fs/promises' +import { createHash } from 'crypto' +import path from 'path' + +const filePath = path.resolve( + import.meta.dirname, + 'files/fileToCalculateHashFor.txt' +) + const calculateHash = async () => { - // Write your code here -}; + const textFromFile = await readFile(filePath) + const hash = createHash('sha256').update(textFromFile) + console.log(hash.digest('hex')) +} -await calculateHash(); +await calculateHash() diff --git a/src/modules/cjsToEsm.cjs b/src/modules/cjsToEsm.cjs deleted file mode 100644 index 089bd2db13..0000000000 --- a/src/modules/cjsToEsm.cjs +++ /dev/null @@ -1,34 +0,0 @@ -const path = require('node:path'); -const { release, version } = require('node:os'); -const { createServer: createServerHttp } = require('node:http'); - -require('./files/c.cjs'); - -const random = Math.random(); - -const unknownObject = random > 0.5 ? require('./files/a.json') : require('./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}`); - -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'); -}); - -module.exports = { - unknownObject, - myServer, -}; diff --git a/src/modules/esm.mjs b/src/modules/esm.mjs new file mode 100644 index 0000000000..9726dda5ee --- /dev/null +++ b/src/modules/esm.mjs @@ -0,0 +1,36 @@ +import path from 'path' +import { release, version } from 'node:os' +import { createServer as createServerHttp } from 'node:http' +import { fileURLToPath } from 'node:url' + +import './files/c.cjs' + +const random = Math.random() + +const unknownObject = await (random > 0.5 + ? import('./files/a.json', { with: { type: 'json' } }) + : import('./files/b.json', { with: { type: 'json' } })) + +console.log(`Release ${release()}`) +console.log(`Version ${version()}`) +console.log(`Path segment separator is "${path.sep}"`) + +const fileName = fileURLToPath(import.meta.url) +const dirName = path.dirname(fileName) +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 } diff --git a/src/streams/files/fileToWrite.txt b/src/streams/files/fileToWrite.txt index e69de29bb2..e659235805 100644 --- a/src/streams/files/fileToWrite.txt +++ b/src/streams/files/fileToWrite.txt @@ -0,0 +1,12 @@ +rfgdfgdfgfd +gdf +gfd +gfd +g +fdg +fd +g +fdg + + + diff --git a/src/streams/read.js b/src/streams/read.js index e3938be563..45b70c60d5 100644 --- a/src/streams/read.js +++ b/src/streams/read.js @@ -1,5 +1,11 @@ +import { createReadStream } from 'fs' +import path from 'path' + +const filePath = path.resolve(import.meta.dirname, 'files/fileToRead.txt') + const read = async () => { - // Write your code here -}; + const readStream = createReadStream(filePath, 'utf8') + readStream.pipe(process.stdout) +} -await read(); +await read() diff --git a/src/streams/transform.js b/src/streams/transform.js index 9e6c15fe84..e3d53627f8 100644 --- a/src/streams/transform.js +++ b/src/streams/transform.js @@ -1,5 +1,27 @@ +import { Transform } from 'stream' + const transform = async () => { - // Write your code here -}; + const upperCaseTransform = new Transform({ + transform(chunk, encoding, callback) { + callback(null, chunk.toString().toUpperCase()) + }, + }) + + process.stdin.pipe(upperCaseTransform).pipe(process.stdout) +} + +await transform() + +// class UpperCaseTransform extends Transform { +// _transform(chunk, encoding, callback) { +// callback(null, chunk.toString().toUpperCase()) +// } +// } + +// const transform = async () => { +// const transformUpperStream = new UpperCaseTransform() + +// process.stdin.pipe(transformUpperStream).pipe(process.stdout) +// } -await transform(); +// await transform() diff --git a/src/streams/write.js b/src/streams/write.js index 84aa11e7cb..3bd892bbf3 100644 --- a/src/streams/write.js +++ b/src/streams/write.js @@ -1,5 +1,12 @@ +import { createWriteStream } from 'fs' +import path from 'path' + +const filePath = path.resolve(import.meta.dirname, 'files/fileToWrite.txt') + const write = async () => { - // Write your code here -}; + const writeStream = createWriteStream(filePath, 'utf8', { flags: 'a' }) + process.stdin.setEncoding('utf8') + process.stdin.pipe(writeStream) +} -await write(); +await write() diff --git a/src/wt/main.js b/src/wt/main.js index e2ef054d41..861ed9baa3 100644 --- a/src/wt/main.js +++ b/src/wt/main.js @@ -1,5 +1,35 @@ +import path from 'path' +import { cpus } from 'os' +import { Worker } from 'worker_threads' + +const workerPath = path.resolve(import.meta.dirname, 'worker.js') +const START_INDEX = 10 + const performCalculations = async () => { - // Write your code here -}; + const countCPU = cpus().length + const workerPromises = [] + + for (let i = 0; i < countCPU; i++) { + const workerData = START_INDEX + i + + const workerPromise = new Promise(resolve => { + const worker = new Worker(workerPath, { workerData }) + + worker.on('message', data => { + resolve({ status: 'resolved', data }) + worker.terminate() + }) + + worker.on('error', error => { + resolve({ status: 'resolved', data: null }) + }) + }) + + workerPromises.push(workerPromise) + } + + const result = await Promise.all(workerPromises) + console.log(result) +} -await performCalculations(); +await performCalculations() diff --git a/src/wt/worker.js b/src/wt/worker.js index 405595394d..bdc6956949 100644 --- a/src/wt/worker.js +++ b/src/wt/worker.js @@ -1,8 +1,11 @@ +import { parentPort, workerData } from 'worker_threads' + // n should be received from main thread -const nthFibonacci = (n) => n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2); +const nthFibonacci = n => + n < 2 ? n : nthFibonacci(n - 1) + nthFibonacci(n - 2) const sendResult = () => { - // This function sends result of nthFibonacci computations to main thread -}; + parentPort.postMessage(nthFibonacci(workerData)) +} -sendResult(); +sendResult() diff --git a/src/zip/compress.js b/src/zip/compress.js index d55209587e..041908d5c7 100644 --- a/src/zip/compress.js +++ b/src/zip/compress.js @@ -1,5 +1,18 @@ +import path from 'path' +import zlib from 'zlib' +import { createReadStream, createWriteStream } from 'fs' + +const filePathInput = path.resolve( + import.meta.dirname, + 'files/fileToCompress.txt' +) +const filePathOutput = path.resolve(import.meta.dirname, 'files/archive.gz') + const compress = async () => { - // Write your code here -}; + const readStream = createReadStream(filePathInput) + const writeStream = createWriteStream(filePathOutput) + + readStream.pipe(zlib.createGzip()).pipe(writeStream) +} -await compress(); +await compress() diff --git a/src/zip/decompress.js b/src/zip/decompress.js index 8aaf26c8a4..1125f699d7 100644 --- a/src/zip/decompress.js +++ b/src/zip/decompress.js @@ -1,5 +1,31 @@ +import path from 'path' +import zlib from 'zlib' +import { createReadStream, createWriteStream } from 'fs' +import { pipeline } from 'stream' + +const archivePathInput = path.resolve(import.meta.dirname, 'files/archive.gz') +const archivePathOutput = path.resolve( + import.meta.dirname, + 'files/fileToCompress.txt' +) + const decompress = async () => { - // Write your code here -}; + // const readStream = createReadStream(archivePathInput) + // const writeStream = createWriteStream(archivePathOutput) + // readStream.pipe(zlib.createGunzip()).pipe(writeStream) + + pipeline( + createReadStream(archivePathInput), + zlib.createGunzip(), + createWriteStream(archivePathOutput), + err => { + if (err) { + console.error('Ошибка при распаковке:', err.message) + } else { + console.log('Извлечение завершено успешно') + } + } + ) +} -await decompress(); +await decompress() diff --git a/src/zip/files/archive.gz b/src/zip/files/archive.gz new file mode 100644 index 0000000000..87e36da4f0 Binary files /dev/null and b/src/zip/files/archive.gz differ diff --git a/utils.js b/utils.js new file mode 100644 index 0000000000..85dacbbfe3 --- /dev/null +++ b/utils.js @@ -0,0 +1,8 @@ +import { promises as fs } from 'fs' + +export async function isFileExists(folderPath) { + return await fs + .access(folderPath) + .then(() => true) + .catch(() => false) +}