From d5d9da4864113ffdcebe893c487a95e796a48a93 Mon Sep 17 00:00:00 2001 From: yuranius Date: Mon, 19 Dec 2022 11:40:37 +0300 Subject: [PATCH] feat: end project --- README.md | 230 ++++++++++++++++++++++++++++- package.json | 20 +++ src/index.js | 35 +++++ src/router.js | 77 ++++++++++ src/services/add.js | 15 ++ src/services/cat.js | 25 ++++ src/services/cd.js | 16 ++ src/services/compressDecompress.js | 43 ++++++ src/services/copyAndRemove.js | 37 +++++ src/services/hash.js | 16 ++ src/services/index.js | 11 ++ src/services/ls.js | 24 +++ src/services/os.js | 26 ++++ src/services/remove.js | 21 +++ src/services/rename.js | 14 ++ src/services/up.js | 9 ++ src/utils/const.js | 10 ++ src/utils/deleteFile.js | 5 + src/utils/dirPath.js | 6 + src/utils/exitProcess.js | 21 +++ src/utils/filterSortTable.js | 6 + src/utils/index.js | 3 + src/utils/setTable.js | 22 +++ src/utils/transformArgs.js | 20 +++ src/utils/validationAndCheck.js | 11 ++ src/utils/workerForSetTable.js | 14 ++ 26 files changed, 736 insertions(+), 1 deletion(-) create mode 100644 package.json create mode 100644 src/index.js create mode 100644 src/router.js create mode 100644 src/services/add.js create mode 100644 src/services/cat.js create mode 100644 src/services/cd.js create mode 100644 src/services/compressDecompress.js create mode 100644 src/services/copyAndRemove.js create mode 100644 src/services/hash.js create mode 100644 src/services/index.js create mode 100644 src/services/ls.js create mode 100644 src/services/os.js create mode 100644 src/services/remove.js create mode 100644 src/services/rename.js create mode 100644 src/services/up.js create mode 100644 src/utils/const.js create mode 100644 src/utils/deleteFile.js create mode 100644 src/utils/dirPath.js create mode 100644 src/utils/exitProcess.js create mode 100644 src/utils/filterSortTable.js create mode 100644 src/utils/index.js create mode 100644 src/utils/setTable.js create mode 100644 src/utils/transformArgs.js create mode 100644 src/utils/validationAndCheck.js create mode 100644 src/utils/workerForSetTable.js diff --git a/README.md b/README.md index 9cfda00..9ae9c8d 100644 --- a/README.md +++ b/README.md @@ -1 +1,229 @@ -# NodeJS_Task-2_file-manager \ No newline at end of file +# Help + +## `up` +Go upper from current directory +## `cd` +Go to dedicated folder from current directory + +`!!! Arguments are entered without quotes` + +example: +```bash +/home/yuranius/>cd test // /home/yuranius/test +/home/yuranius/>cd test/1 // /home/yuranius/test/1 +/home/yuranius/>cd /home // /home +``` +## `ls` +Print in console list of all files and folders in current directory. + +## `cat path_to_file` +Read file and print it's content in console + +`!!! Arguments are entered without quotes` +example: +```bash + /home/yuranius/test/1>cat test +``` + +## `add new_file_name` +Create empty file in current working directory + +`!!! Arguments are entered without quotes` + +## `rn path_to_file new_filename` +Rename file + +`!!! Quotes are used` + +example: +```bash + /home/yuranius/test>rn 'test.txt' 'test2.txt' +``` + +## `cp path_to_file path_to_new_directory` +Copy file + +`!!! Quotes are used` + +## `mv path_to_file path_to_new_directory` +Move file + +`!!! Quotes are used` + +## `rm path_to_file` +Delete file + +`!!! Arguments are entered without quotes` + +## `os` + + +## `hash path_to_file` +Calculate hash for file and print it into console + +## `compress path_to_file path_to_destination` +Compress file + +`!!! Quotes are used` +## `decompress path_to_file path_to_destination` +Decompress file + +`!!! Quotes are used` + +# Scoring: File Manager +## Basic Scope +- General + - **+6** Application accepts username and prints proper message + - **+10** Application exits if user pressed `ctrl+c` or sent `.exit` command and proper message is printed +- Operations fail + - **+20** Attempts to perform an operation on a non-existent file or work on a non-existent path result in the operation fail + - **+10** Operation fail doesn't crash application +- Navigation & working directory operations implemented properly + - **+10** Go upper from current directory + - **+10** Go to dedicated folder from current directory + - **+20** List all files and folders in current directory +- Basic operations with files implemented properly + - **+10** Read file and print it's content in console + - **+10** Create empty file + - **+10** Rename file + - **+10** Copy file + - **+10** Move file + - **+10** Delete file +- Operating system info (prints following information in console) implemented properly + - **+6** Get EOL (default system End-Of-Line) + - **+10** Get host machine CPUs info (overall amount of CPUS plus model and clock rate (in GHz) for each of them) + - **+6** Get home directory + - **+6** Get current *system user name* (Do not confuse with the username that is set when the application starts) + - **+6** Get CPU architecture for which Node.js binary has compiled +- Hash calculation implemented properly + - **+20** Calculate hash for file +- Compress and decompress operations + - **+20** Compress file (using Brotli algorithm) + - **+20** Decompress file (using Brotli algorithm) + +## Advanced Scope + +- **+30** All operations marked as to be implemented using certain streams should be performed using Streams API +- **+20** No synchronous Node.js API with asynchronous analogues is used (e.g. not used `readFileSync` instead of `readFile`) +- **+20** Codebase is written in ESM modules instead of CommonJS +- **+20** Codebase is separated (at least 7 modules) + + +## Total: `330 points` + +# Assignment: File Manager + +## Description + +Your task is to implement File Manager using Node.js APIs. + +The file manager should be able to do the following: + +- Work using CLI +- Perform basic file operations (copy, move, delete, rename, etc.) +- Utilize Streams API +- Get information about the host machine operating system +- Perform hash calculations +- Compress and decompress files + +## Technical requirements + +- No external dependencies should be required +- Use 18 LTS version of Node.js +- The program is started by npm-script `start` in following way: +```bash +npm run start -- --username=your_username +``` +- After starting the program displays the following text in the console (`Username` is equal to value that was passed on application start in `--username` CLI argument) +`Welcome to the File Manager, Username!` +- After program work finished (`ctrl + c` pressed or user sent `.exit` command into console) the program displays the following text in the console +`Thank you for using File Manager, Username, goodbye!` +- At the start of the program and after each end of input/operation current working directory should be printed in following way: +`You are currently in path_to_working_directory` +- Starting working directory is current user's home directory (for example, on Windows it's something like `system_drive/Users/Username`) +- By default program should prompt user in console to print commands and wait for results +- In case of unknown operation or invalid input (missing mandatory arguments, wrong data in arguments, etc.) `Invalid input` message should be shown and user should be able to enter another command +- In case of error during execution of operation `Operation failed` message should be shown and user should be able to enter another command (e.g. attempt to perform an operation on a non-existent file or work on a non-existent path should result in the operation fail) +- User can't go upper than root directory (e.g. on Windows it's current local drive root). If user tries to do so, current working directory doesn't change + +List of operations and their syntax: +- Navigation & working directory (nwd) + - Go upper from current directory (when you are in the root folder this operation shouldn't change working directory) + ```bash + up + ``` + - Go to dedicated folder from current directory (`path_to_directory` can be relative or absolute) + ```bash + cd path_to_directory + ``` + - Print in console list of all files and folders in current directory. List should contain: + - list should contain files and folder names (for files - with extension) + - folders and files are sorted in alphabetical order ascending, but list of folders goes first + - type of directory content should be marked explicitly (e.g. as a corresponding column value) + ```bash + ls + ``` + Example of how `ls` command output may look like + ![ls output example](./ls-example.JPG) +- Basic operations with files + - Read file and print it's content in console (should be done using Readable stream): + ```bash + cat path_to_file + ``` + - Create empty file in current working directory: + ```bash + add new_file_name + ``` + - Rename file (content should remain unchanged): + ```bash + rn path_to_file new_filename + ``` + - Copy file (should be done using Readable and Writable streams): + ```bash + cp path_to_file path_to_new_directory + ``` + - Move file (same as copy but initial file is deleted, copying part should be done using Readable and Writable streams): + ```bash + mv path_to_file path_to_new_directory + ``` + - Delete file: + ```bash + rm path_to_file + ``` +- Operating system info (prints following information in console) + - Get EOL (default system End-Of-Line) and print it to console + ```bash + os --EOL + ``` + - Get host machine CPUs info (overall amount of CPUS plus model and clock rate (in GHz) for each of them) and print it to console + ```bash + os --cpus + ``` + - Get home directory and print it to console + ```bash + os --homedir + ``` + - Get current *system user name* (Do not confuse with the username that is set when the application starts) and print it to console + ```bash + os --username + ``` + - Get CPU architecture for which Node.js binary has compiled and print it to console + ```bash + os --architecture + ``` +- Hash calculation + - Calculate hash for file and print it into console + ```bash + hash path_to_file + ``` +- Compress and decompress operations + - Compress file (using Brotli algorithm, should be done using Streams API) + ```bash + compress path_to_file path_to_destination + ``` + - Decompress file (using Brotli algorithm, should be done using Streams API) + ```bash + decompress path_to_file path_to_destination + ``` + NB! After decompressing of previously compressed file result should not differ with originally compressed file + diff --git a/package.json b/package.json new file mode 100644 index 0000000..aa82722 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "nodejs_task-2_file-manager", + "version": "1.0.0", + "description": "", + "main": "src/index.js", + "type": "module", + "scripts": { + "start": "node src/index.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/webjsmaster/NodeJS_Task-2_file-manager.git" + }, + "author": "web-js-master", + "license": "ISC", + "bugs": { + "url": "https://github.com/webjsmaster/NodeJS_Task-2_file-manager/issues" + }, + "homepage": "https://github.com/webjsmaster/NodeJS_Task-2_file-manager#readme" +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..101aec8 --- /dev/null +++ b/src/index.js @@ -0,0 +1,35 @@ +import Emitter from "events"; +import { createInterface } from "readline"; +import { EOL, homedir} from "os"; +import { exit, exitProcess } from "./utils/exitProcess.js"; +import { router } from "./router.js"; + +export const emitter = new Emitter(); + +const args = Object.fromEntries( + process.argv.slice(2).map((arg) => { + const [key, value] = arg.split("="); + return [key, value]; + }) +); + +process.chdir(homedir()); + +const username = args["--username"] ? `\x1b[35m ${args["--username"]} \x1b[0m` : "\x1b[31m stranger \x1b[0m"; + +console.log(`\x1b[33mWelcome to the File Manager, ${username}! \x1b[0m`, EOL); +console.log(`\x1b[36mYou are currently in ${process.cwd()}\x1b[0m`, EOL); + +let rl = createInterface(process.stdin, process.stdout); +rl.setPrompt(`\x1b[32m ${process.cwd()}>\x1b[0m`); +rl.prompt(); + +router(rl); + +rl.on("SIGINT", () => rl.close()); + +rl.on("close", function () { + exit(username); +}); + +exitProcess({ rl, username }); diff --git a/src/router.js b/src/router.js new file mode 100644 index 0000000..67d897f --- /dev/null +++ b/src/router.js @@ -0,0 +1,77 @@ +import { EOL } from "os"; +import { add, cat, cd, compressDecompress, copyAndRemove, hash, ls, os, remove, rename, up } from "./services/index.js"; +import { INVALID_ERROR } from "./utils/const.js"; + + + +export const router = async (rl) => { + rl.on("line", async function (line) { + let [command, ...args] = line.split(' '); + + switch (command) { + case "cd": { + cd(args); + break; + }; + case "ls": { + await ls(); + break; + }; + case "up": { + up(); + break; + }; + case "cat": { + await cat(args); + break; + }; + case "add": { + await add(args); + break; + }; + case "rn": { + await rename(args); + break; + }; + case "cp": { + await copyAndRemove({args}); + break; + }; + case "mv": { + await copyAndRemove({args, del: true}); + break; + }; + case "rm": { + await remove(args); + break; + }; + case "hash": { + await hash(args); + break; + }; + case "compress": { + await compressDecompress({args}); + break; + }; + case "decompress": { + await compressDecompress({args, decompress: true}); + break; + }; + case "os": { + await os(args); + break; + } + case ".exit": { + rl.close() + break; + }; + default: { + console.log(INVALID_ERROR); + break; + }; + } + console.log(`\x1b[36mYou are currently in ${process.cwd()}\x1b[0m`); + rl.setPrompt(`\x1b[32m ${process.cwd()}>\x1b[0m`); + rl.prompt(); + }) +} \ No newline at end of file diff --git a/src/services/add.js b/src/services/add.js new file mode 100644 index 0000000..01863cf --- /dev/null +++ b/src/services/add.js @@ -0,0 +1,15 @@ +import { writeFile } from "fs/promises" +import { OPERATION_ERROR } from "../utils/const.js"; +import { transformArgs} from '../utils/transformArgs.js'; + +export async function add (args) { + + const dir = transformArgs(args) + + try { + await writeFile(dir, '', { flag: 'wx'}); + console.log('File created'); + } catch (e) { + console.error(OPERATION_ERROR); + } +} \ No newline at end of file diff --git a/src/services/cat.js b/src/services/cat.js new file mode 100644 index 0000000..88c68d5 --- /dev/null +++ b/src/services/cat.js @@ -0,0 +1,25 @@ +import { createReadStream } from 'fs'; +import path from "path"; +import { OPERATION_ERROR } from '../utils/const.js'; + +export async function cat (args) { + return new Promise((resolve) => { + const trimArgs = args.join(' ').trim(); + const dir = path.resolve(trimArgs.toString()) + + const rs = createReadStream(dir, { encoding: "utf-8" }); + + rs.on("data", async (chunk) => { + process.stdout.write(chunk) + console.log(''); + }); + + rs.on("error", () => { + resolve(console.log(OPERATION_ERROR)); + }); + + rs.on("end", () => { + resolve(); + }); + }); +} \ No newline at end of file diff --git a/src/services/cd.js b/src/services/cd.js new file mode 100644 index 0000000..b9d7082 --- /dev/null +++ b/src/services/cd.js @@ -0,0 +1,16 @@ +import { resolve } from 'path' +import { INVALID_ERROR, OPERATION_ERROR } from '../utils/const.js'; + +export function cd(args) { + let dir = args.join(' ') + if (dir && dir !== 'cd'){ + try { + process.chdir(resolve( process.cwd(), `${dir}`)); + } catch (error) { + console.error(OPERATION_ERROR); + } + } else { + console.error(INVALID_ERROR); + } +} + diff --git a/src/services/compressDecompress.js b/src/services/compressDecompress.js new file mode 100644 index 0000000..10ef50a --- /dev/null +++ b/src/services/compressDecompress.js @@ -0,0 +1,43 @@ +import { errorMessage, transformArgs } from "../utils/index.js"; +import { createReadStream, createWriteStream, statSync } from "fs"; +import { createBrotliCompress, createBrotliDecompress, constants } from "zlib"; +import { readFile } from "fs/promises"; +import { promisify } from "util"; +import { pipeline } from "stream"; + +export async function compressDecompress({args, decompress}) { + const dir = transformArgs(args); + const zipName = dir + ".gz"; + const unZipName = dir.split(".").slice(0, -1).join("."); + + if (!args.toString().trim().length) { + return errorMessage(); + } + + const pipe = promisify(pipeline); + + async function do_gzip(input, output) { + const zip = decompress + ? createBrotliDecompress() + : createBrotliCompress({ + chunkSize: 32 * 1024, + params: { + [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT, + [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MIN_QUALITY, + [constants.BROTLI_PARAM_SIZE_HINT]: statSync(dir).size, + }, + }); + + const source = createReadStream(input); + const destination = createWriteStream(output); + await pipe(source, zip, destination); + } + + try { + await readFile(dir); + await do_gzip(dir, decompress ? unZipName : zipName); + console.log(`${decompress ? "Decompress" : "Compress"} operation success!`); + } catch (error) { + errorMessage('File not find'); + } +} diff --git a/src/services/copyAndRemove.js b/src/services/copyAndRemove.js new file mode 100644 index 0000000..b992653 --- /dev/null +++ b/src/services/copyAndRemove.js @@ -0,0 +1,37 @@ +import { errorMessage } from "../utils/const.js"; +import { transformArgs } from "../utils/transformArgs.js"; +import { createReadStream, createWriteStream } from "fs"; + +import { validationAndCheck } from "../utils/validationAndCheck.js"; +import { deleteFile } from "../utils/deleteFile.js"; +import path from "path"; + + +export async function copyAndRemove({args, del}) { + const dir = transformArgs(args); + + async function actionFile (file) { + const readStream = createReadStream(dir.one_file); + const writeStream = createWriteStream(path.resolve(dir.two_file, dir.arg_one)); + readStream.pipe(writeStream); + + readStream.on ('end', () => { + if (del) { + deleteFile(file); + } + }) + } + + let res = await validationAndCheck(dir.one_file, dir.two_file, path.resolve(dir.two_file, dir.arg_one)); + + if (res === "open") { + errorMessage("File not find"); + } else if (res === "access") { + errorMessage("Destination folder not find"); + } else if (res?.dev) { + errorMessage("The file already exists in the destination folder"); + } else { + await actionFile(dir.one_file); + console.log(`File ${(del) ? 'moved' : 'copied'} ${dir.two_file}`); + } +} diff --git a/src/services/hash.js b/src/services/hash.js new file mode 100644 index 0000000..9e558c1 --- /dev/null +++ b/src/services/hash.js @@ -0,0 +1,16 @@ +import { transformArgs } from "../utils/transformArgs.js"; +import { readFile } from "fs/promises" +import { errorMessage } from "../utils/const.js"; +import { createHash } from "crypto" + +export async function hash (args) { + const dir = transformArgs(args); + + try { + const file = await readFile(dir); + const hash = createHash('sha256').update(file).digest('hex'); + console.log(hash); + } catch (error) { + errorMessage('File not find'); + } +} \ No newline at end of file diff --git a/src/services/index.js b/src/services/index.js new file mode 100644 index 0000000..3867079 --- /dev/null +++ b/src/services/index.js @@ -0,0 +1,11 @@ +export * from "./add.js"; +export * from "./cat.js"; +export * from "./cd.js"; +export * from "./copyAndRemove.js"; +export * from "./ls.js"; +export * from "./os.js"; +export * from "./remove.js"; +export * from "./rename.js"; +export * from "./up.js"; +export * from "./hash.js"; +export * from "./compressDecompress.js"; diff --git a/src/services/ls.js b/src/services/ls.js new file mode 100644 index 0000000..92ecd24 --- /dev/null +++ b/src/services/ls.js @@ -0,0 +1,24 @@ +import path from "path"; +import fs from "fs/promises"; +import { OPERATION_ERROR } from "../utils/const.js"; +import { setTable } from "../utils/setTable.js"; +import { filterSortTable } from "../utils/filterSortTable.js"; + + +export async function ls() { + try { + const files = await fs.readdir(path.resolve(process.cwd())); + let table = await setTable(files); + + const typeFile = filterSortTable(table, 'file'); + const typeUndefined = filterSortTable(table, 'undefined'); + const typeError = filterSortTable(table, 'error'); + const typeDirectory = filterSortTable(table, 'directory'); + + let result = typeDirectory.concat(typeFile, typeUndefined, typeError) + + console.table(result); + } catch (error) { + console.error(OPERATION_ERROR); + } +} diff --git a/src/services/os.js b/src/services/os.js new file mode 100644 index 0000000..1b3e582 --- /dev/null +++ b/src/services/os.js @@ -0,0 +1,26 @@ +import { errorMessage } from "../utils/const.js"; +import { cpus, EOL, userInfo } from 'os' + +export async function os(args) { + try { + const { username, homedir } = userInfo() + + const cpusInfo = cpus().map(({ model, speed }) => { + return { model, speed: `${speed / 1000}GHz`} + }) + + const info = { + '--EOL': JSON.stringify(EOL), + '--cpus': cpusInfo, + '--homedir': homedir, + '--username': username, + '--architecture': process.arch, + } + + if (!info[args]) throw new Error('No such parameter') + + console.table(info[args]); + } catch (error) { + errorMessage(error.message); + } +} \ No newline at end of file diff --git a/src/services/remove.js b/src/services/remove.js new file mode 100644 index 0000000..1611558 --- /dev/null +++ b/src/services/remove.js @@ -0,0 +1,21 @@ +import { errorMessage } from "../utils/const.js"; +import { transformArgs } from "../utils/transformArgs.js"; +import { readFile } from "fs/promises" +import { deleteFile } from "../utils/deleteFile.js"; + + +export async function remove(args) { + if (!args.toString().trim().length) { + return errorMessage(); + } + + const dir = transformArgs(args); + + try { + await readFile(dir); + await deleteFile(dir); + console.info("File delete") + } catch (error) { + errorMessage('File not find') + } +} diff --git a/src/services/rename.js b/src/services/rename.js new file mode 100644 index 0000000..0d9e85e --- /dev/null +++ b/src/services/rename.js @@ -0,0 +1,14 @@ +import { rename as renaming } from 'fs/promises' +import { OPERATION_ERROR } from '../utils/const.js'; +import { transformArgs } from "../utils/transformArgs.js"; + +export async function rename (args) { + const dir = transformArgs(args); + + try { + await renaming(dir.one_file, dir.two_file); + console.log(`File renamed to "${dir.arg_two}"`); + } catch (error) { + console.error(OPERATION_ERROR); + } +} \ No newline at end of file diff --git a/src/services/up.js b/src/services/up.js new file mode 100644 index 0000000..00bdf97 --- /dev/null +++ b/src/services/up.js @@ -0,0 +1,9 @@ +import { OPERATION_ERROR } from "../utils/const.js"; + +export async function up ( ) { + try { + process.chdir('..'); + } catch (error) { + console.error(OPERATION_ERROR); + } +} \ No newline at end of file diff --git a/src/utils/const.js b/src/utils/const.js new file mode 100644 index 0000000..45b8082 --- /dev/null +++ b/src/utils/const.js @@ -0,0 +1,10 @@ +export const OPERATION_ERROR = '\x1b[31mOperation failed\x1b[0m'; +export const INVALID_ERROR = '\x1b[33mInvalid input\x1b[0m'; + +export function errorMessage (message) { + if (!message) { + console.error(`\x1b[31mError: ${OPERATION_ERROR}\x1b[0m`); + } else { + console.error(`\x1b[31mError: ${message}\x1b[0m`); + } +} \ No newline at end of file diff --git a/src/utils/deleteFile.js b/src/utils/deleteFile.js new file mode 100644 index 0000000..66f026b --- /dev/null +++ b/src/utils/deleteFile.js @@ -0,0 +1,5 @@ +import { unlink } from "fs/promises"; + +export async function deleteFile (file) { + unlink(file) +} \ No newline at end of file diff --git a/src/utils/dirPath.js b/src/utils/dirPath.js new file mode 100644 index 0000000..77d7dea --- /dev/null +++ b/src/utils/dirPath.js @@ -0,0 +1,6 @@ +import { fileURLToPath } from 'url'; +import { dirname } from 'path'; + +export const dirPath = async (url) => { + return dirname(fileURLToPath(url)); +} \ No newline at end of file diff --git a/src/utils/exitProcess.js b/src/utils/exitProcess.js new file mode 100644 index 0000000..cba0ed3 --- /dev/null +++ b/src/utils/exitProcess.js @@ -0,0 +1,21 @@ +import { platform , EOL } from 'os' + +export function exit (username) { + console.log(EOL, `\x1b[33mThank you for using File Manager, ${username},\x1b[33m goodbye! 📢 \x1b[0m`); + process.exit(0); +} + +export const exitProcess = ({rl, username}) => { + if (platform() === 'linux') { + rl.on('SIGTSTP', function () { + exit(username); + }) + } else if (platform() === 'win32') { + rl.on('SIGINT', function () { + exit(username); + }) + } else { + console.log('📢 SORRY!!! ERROR EVENT!!!'); + } +} + diff --git a/src/utils/filterSortTable.js b/src/utils/filterSortTable.js new file mode 100644 index 0000000..67090ab --- /dev/null +++ b/src/utils/filterSortTable.js @@ -0,0 +1,6 @@ +export function filterSortTable (table, type) { + return table.filter ( t => t.Type === type) + .sort( function (a, b) { + return a.Name.localeCompare(b.Name); + }) +} \ No newline at end of file diff --git a/src/utils/index.js b/src/utils/index.js new file mode 100644 index 0000000..e068efb --- /dev/null +++ b/src/utils/index.js @@ -0,0 +1,3 @@ +export * from "./const.js"; +export * from "./transformArgs.js"; +export * from "./validationAndCheck.js"; diff --git a/src/utils/setTable.js b/src/utils/setTable.js new file mode 100644 index 0000000..26a6542 --- /dev/null +++ b/src/utils/setTable.js @@ -0,0 +1,22 @@ +import { rejects } from "assert"; +import { Worker } from "worker_threads"; +import { dirPath } from "./dirPath.js"; + + + +export async function setTable(files) { + const workerFile = `${await dirPath(import.meta.url)}/workerForSetTable.js`; + + const arrResult = await Promise.all( + files.map((file) => { + return new Promise((res, rej) => { + const worker = new Worker(workerFile, { + workerData: file, + }); + worker.on('message', (msg) => res(msg)); + worker.on('error', (msg) => rej(msg)); + }); + }) + ); + return arrResult; +} diff --git a/src/utils/transformArgs.js b/src/utils/transformArgs.js new file mode 100644 index 0000000..fc6a5bc --- /dev/null +++ b/src/utils/transformArgs.js @@ -0,0 +1,20 @@ +import path from "path"; + +export function transformArgs(args) { + if (args.toString().startsWith("'")) { + const arrArgs = args.join(" ").trim().split("'"); + + if (arrArgs.length === 3) { + return path.resolve(arrArgs[1]); + } else if (arrArgs.length === 5) { + return { + one_file: path.resolve(arrArgs[1].trim()), + two_file: path.resolve(arrArgs[3].trim()), + arg_one: arrArgs[1].trim(), + arg_two: arrArgs[3].trim(), + }; + } + } else { + return path.resolve(args.join(" ").trim().toString()); + } +} diff --git a/src/utils/validationAndCheck.js b/src/utils/validationAndCheck.js new file mode 100644 index 0000000..c4337b9 --- /dev/null +++ b/src/utils/validationAndCheck.js @@ -0,0 +1,11 @@ +import { stat, readFile, access } from "fs/promises"; + +export async function validationAndCheck(dir1, dir2, file) { + try { + await readFile(dir1); + await access(dir2); + return await stat(file); + } catch (error) { + return error?.syscall; + } +} \ No newline at end of file diff --git a/src/utils/workerForSetTable.js b/src/utils/workerForSetTable.js new file mode 100644 index 0000000..af4ceea --- /dev/null +++ b/src/utils/workerForSetTable.js @@ -0,0 +1,14 @@ +import { parentPort, workerData } from 'worker_threads'; +import fs from "fs/promises"; + +const worker = async () => { + try { + const stat = await fs.lstat(workerData); + const type = stat.isFile() === true ? 'file' : stat.isDirectory() === true ? 'directory' : 'error' + parentPort.postMessage({Name: workerData, Type: type}) + } catch (error) { + parentPort.postMessage({Name: workerData, Type: 'undefined'}) + } + +} +worker(); \ No newline at end of file