From d08cc0f3509880509f30babc7d53412077686137 Mon Sep 17 00:00:00 2001 From: Philipp Kunz Date: Tue, 2 Apr 2024 20:53:02 +0200 Subject: [PATCH] fix(core): update --- npmextra.json | 4 +- readme.md | 211 +++++++++++++++--------- ts/00_commitinfo_data.ts | 2 +- ts/classes.smartfile.ts | 2 +- ts/classes.streamfile.ts | 2 +- ts/classes.virtualdirectory.ts | 2 +- ts/fs.ts | 47 +++++- ts/fsstream.ts | 4 +- ts/index.ts | 2 +- ts/interpreter.ts | 2 +- ts/memory.ts | 2 +- ts/{smartfile.plugins.ts => plugins.ts} | 0 12 files changed, 188 insertions(+), 92 deletions(-) rename ts/{smartfile.plugins.ts => plugins.ts} (100%) diff --git a/npmextra.json b/npmextra.json index 4cf2dc5..38e8a8a 100644 --- a/npmextra.json +++ b/npmextra.json @@ -15,7 +15,9 @@ "license": "MIT" } }, - "tsdocs": { + "tsdoc": { + "classes": ["SmartFile", "StreamFile"], + "descriptions": ["the purpose of the StreamFile class is to provide a hybrid interface between streaming files and simple handling when writing and reading those files multiple times."], "legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n" } } \ No newline at end of file diff --git a/readme.md b/readme.md index 49833d4..fe93490 100644 --- a/readme.md +++ b/readme.md @@ -1,126 +1,175 @@ -# SmartFile -> SmartFile offers smart ways to work with files in nodejs. +# @push.rocks/smartfile + +[@push.rocks/smartfile offers smart ways to work with files in nodejs](https://gitlab.com/push.rocks/smartfile#readme) ## Install -To install SmartFile, use npm or Yarn as follows: -``` -npm install @push.rocks/smartfile --save -``` -Or: -``` -yarn add @push.rocks/smartfile +To install `@push.rocks/smartfile`, run the following command in your project directory: + +```bash +npm install @push.rocks/smartfile ``` ## Usage -SmartFile is a comprehensive toolkit for file manipulation in Node.js. It provides functionalities for working with the filesystem, in-memory operations, streaming, and handling virtual directories. Below, you will find examples showcasing how to utilize these functionalities effectively. +The `@push.rocks/smartfile` library offers a comprehensive suite of tools to work with files in Node.js projects, facilitating a variety of file operations such as reading, writing, streaming, and in-memory manipulation. Below, you'll find detailed examples illustrating how to leverage the library's functionality to tackle real-world tasks. -### Basic File Operations +### Working with Filesystem -For reading and writing files, SmartFile provides synchronous and asynchronous methods. Here’s how you can use them: - -#### Async Write to File +#### Ensuring File and Directory Existence ```typescript -import { memory } from '@push.rocks/smartfile'; +import { fs } from '@push.rocks/smartfile'; -const myData: string = 'Hello, SmartFile!'; +// Ensure a file exists with initial content (Async) +await fs.ensureFile('./path/to/new/file.txt', 'Initial content'); -// Writing string data to a file asynchronously -memory.toFs(myData, './data/hello.txt'); +// Ensure a directory exists (Async) +await fs.ensureDir('./path/to/new/dir'); ``` -#### Sync Write to File +#### Getting File Details ```typescript -import { memory } from '@push.rocks/smartfile'; +import { fs } from '@push.rocks/smartfile'; -const myData: string = 'Hello, World!'; +// Check if a file exists (Async) +const exists: boolean = await fs.fileExists('./path/to/file.txt'); -// Writing string data to a file synchronously -memory.toFsSync(myData, './data/helloSync.txt'); +// Check if a path is a directory +const isDir: boolean = fs.isDirectory('./path/to/check'); ``` -### Working with Streams +### Reading and Writing Files -Streaming files to and from the filesystem is made easy with SmartFile. Here’s an example: - -#### Creating Read and Write Streams +#### Basic Reading and Writing ```typescript -import { fsStream } from '@push.rocks/smartfile'; -import * as fs from 'fs'; +import { SmartFile, memory } from '@push.rocks/smartfile'; -// Creating a read stream -const readStream = fsStream.createReadStream('./data/readme.txt'); +// Read a file to a SmartFile instance (Async) +const smartFile: SmartFile = await SmartFile.fromFilePath('./path/to/read/file.txt'); -// Creating a write stream -const writeStream = fsStream.createWriteStream('./data/copy.txt'); +// Write SmartFile instance to a new path (Async) +await smartFile.writeToDir('./path/to/target/dir'); -// Piping the read stream to the write stream -readStream.pipe(writeStream); +// Write text content to a file (Async) +await memory.toFs('Hello SmartFile!', './path/to/output/file.txt'); ``` -### Dealing with Virtual Directories - -Virtual directories allow you to group and manipulate files as if they were in a filesystem structure without actually writing them to disk. - -```typescript -import { VirtualDirectory } from '@push.rocks/smartfile'; - -(async () => { - // Creating a virtual directory from the file system - const virtualDir = await VirtualDirectory.fromFsDirPath('./myDirectory'); - - // Adding files from another virtual directory - const anotherVirtualDir = await VirtualDirectory.fromFsDirPath('./anotherDirectory'); - await virtualDir.addVirtualDirectory(anotherVirtualDir, 'merged'); - - // Saving the virtual directory to disk - await virtualDir.saveToDisk('./outputDirectory'); -})(); -``` - -### Advanced File Manipulation - -SmartFile also allows for more advanced file manipulation techniques through the `SmartFile` class. +#### Working with File Contents ```typescript import { SmartFile } from '@push.rocks/smartfile'; -(async () => { - // Create a SmartFile instance from a file path - const smartFile = await SmartFile.fromFilePath('./data/example.txt'); +// Creating SmartFile instance from text +const smartFileFromText: SmartFile = await SmartFile.fromString('./path/to/text/file.txt', 'Text content here', 'utf8'); - // Edit the file content - await smartFile.editContentAsString(async (currentContent: string) => { - return currentContent.toUpperCase(); - }); +// Reading content from SmartFile instance +const content: string = smartFileFromText.contents.toString(); - // Write the changes back to disk - await smartFile.write(); -})(); +// Editing content of SmartFile +await smartFileFromText.editContentAsString(async (currentContent: string) => `Modified: ${currentContent}`); ``` -### Conversion and Interpretation - -You can easily convert file contents to objects or interpret file types for further processing: +### File Streaming ```typescript -import { memory } from '@push.rocks/smartfile'; +import { StreamFile } from '@push.rocks/smartfile'; -(async () => { - const fileString: string = await fs.promises.readFile('./data/example.json', 'utf8'); - const fileObject = memory.toObject(fileString, 'json'); +// Creating a StreamFile from a file path (Async) +const streamFile: StreamFile = await StreamFile.fromPath('./path/to/large/file.avi'); - console.log(fileObject); - // Proceed with the object... -})(); +// Streaming file content to disk (Async) +await streamFile.writeToDisk('./path/to/target/file.avi'); ``` -SmartFile simplifies handling files in a Node.js environment, providing a concise, promise-based API for various file operations, stream handling, and in-memory file manipulation. Whether you're dealing with physical files on the disk, manipulating file streams, or managing virtual files and directories, SmartFile has got you covered. +#### Utilizing Stream Files from URLs -## Information on Licensing +```typescript +import { StreamFile } from '@push.rocks/smartfile'; -SmartFile is licensed under the MIT License. This permissive license is short and to the point. It lets people do anything they want with your code as long as they provide attribution back to you and don’t hold you liable. \ No newline at end of file +// Creating a StreamFile from URL (Async) +const streamFileFromURL: StreamFile = await StreamFile.fromUrl('https://example.com/data.json'); + +// Accessing StreamFile content as string (Async, for textual data) +const contentAsString: string = await streamFileFromURL.getContentAsString(); +``` + +### Handling Virtual Directories + +```typescript +import { VirtualDirectory, SmartFile } from '@push.rocks/smartfile'; + +// Creating a virtual directory from existing directory on disk (Async) +const virtualDirectory: VirtualDirectory = await VirtualDirectory.fromFsDirPath('./path/to/source/dir'); + +// Adding files to virtual directory +virtualDirectory.addSmartfiles([await SmartFile.fromFilePath('./path/to/extra/file.txt')]); + +// Saving virtual directory to disk (Async) +await virtualDirectory.saveToDisk('./path/to/destination/dir'); +``` + +#### Manipulating File Paths + +```typescript +import { SmartFile } from '@push.rocks/smartfile'; + +// Read SmartFile and change its relative path +const smartFile: SmartFile = await SmartFile.fromFilePath('./path/to/original/file.txt'); +smartFile.updateFileName('newFilename.txt'); // Retains original directory but changes file name +``` + +### Security and Hashing + +```typescript +import { SmartFile } from '@push.rocks/smartfile'; + +// Creating SmartFile instance and getting hash +const smartFileForHash: SmartFile = await SmartFile.fromString('./fileForHashing.txt', 'Content for hashing', 'utf8'); +const hash: string = await smartFileForHash.getHash('content'); // 'content', 'path', or 'all' +``` + +### Advanced Streaming via `SmartReadStream` + +For handling edge cases such as streaming large files that are being written concurrently (e.g., log files), `SmartReadStream` can be employed to monitor files for new data and stream content as it becomes available. + +```typescript +import { fsStream } from '@push.rocks/smartfile'; + +const smartReadStream = new fsStream.SmartReadStream('./path/to/live/file.log'); +smartReadStream + .on('data', (chunk) => { + // Process streamed data + }) + .on('error', (err) => { + console.error('Stream encountered an error:', err); + }) + .on('end', () => { + console.log('No more data available.'); + }); +``` + +In conclusion, `@push.rocks/smartfile` equips developers with a highly versatile API for file manipulation, enhancing productivity in handling file operations within Node.js applications. By leveraging the examples provided, users can efficiently integrate file processing tasks into their projects, streamlining workflows and achieving granular control over file and directory management. + +For more details and advanced use cases, please refer to the `@push.rocks/smartfile` documentation and explore the source code to unlock the full potential of this powerful library in your Node.js applications. + +## License and Legal Information + +This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. + +**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. + +### Trademarks + +This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. + +### Company Information + +Task Venture Capital GmbH +Registered at District court Bremen HRB 35230 HB, Germany + +For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. + +By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. diff --git a/ts/00_commitinfo_data.ts b/ts/00_commitinfo_data.ts index 325167e..dada1fb 100644 --- a/ts/00_commitinfo_data.ts +++ b/ts/00_commitinfo_data.ts @@ -3,6 +3,6 @@ */ export const commitinfo = { name: '@push.rocks/smartfile', - version: '11.0.5', + version: '11.0.6', description: 'offers smart ways to work with files in nodejs' } diff --git a/ts/classes.smartfile.ts b/ts/classes.smartfile.ts index abdf3a7..c1ff150 100644 --- a/ts/classes.smartfile.ts +++ b/ts/classes.smartfile.ts @@ -1,4 +1,4 @@ -import * as plugins from './smartfile.plugins.js'; +import * as plugins from './plugins.js'; import * as fs from './fs.js'; import * as memory from './memory.js'; diff --git a/ts/classes.streamfile.ts b/ts/classes.streamfile.ts index 15ccce9..21a95c5 100644 --- a/ts/classes.streamfile.ts +++ b/ts/classes.streamfile.ts @@ -1,4 +1,4 @@ -import * as plugins from './smartfile.plugins.js'; +import * as plugins from './plugins.js'; import * as smartfileFs from './fs.js'; import * as smartfileFsStream from './fsstream.js'; import { Readable } from 'stream'; diff --git a/ts/classes.virtualdirectory.ts b/ts/classes.virtualdirectory.ts index e527724..0931d36 100644 --- a/ts/classes.virtualdirectory.ts +++ b/ts/classes.virtualdirectory.ts @@ -1,5 +1,5 @@ import { SmartFile } from './classes.smartfile.js'; -import * as plugins from './smartfile.plugins.js'; +import * as plugins from './plugins.js'; import * as fs from './fs.js'; diff --git a/ts/fs.ts b/ts/fs.ts index 7c1dc3b..0952b18 100644 --- a/ts/fs.ts +++ b/ts/fs.ts @@ -1,9 +1,10 @@ -import * as plugins from './smartfile.plugins.js'; +import * as plugins from './plugins.js'; import * as interpreter from './interpreter.js'; import { SmartFile } from './classes.smartfile.js'; import * as memory from './memory.js'; +import type { StreamFile } from './classes.streamfile.js'; /*=============================================================== ============================ Checks ============================= ===============================================================*/ @@ -439,6 +440,50 @@ export const waitForFileToBeReady = (filePathArg: string): Promise => { }); }; +/** + * writes string or Smartfile to disk. + * @param fileArg + * @param fileNameArg + * @param fileBaseArg + */ +export let toFs = async ( + filePathArg: string, + fileContentArg: string | Buffer | SmartFile | StreamFile, + optionsArg: { + respectRelative?: boolean; + } = {} +) => { + const done = plugins.smartpromise.defer(); + + // check args + if (!fileContentArg || !filePathArg) { + throw new Error('expected valid arguments'); + } + + // prepare actual write action + let fileContent: string | Buffer; + let fileEncoding: 'utf8' | 'binary' = 'utf8'; + let filePath: string = filePathArg; + + // handle Smartfile + if (fileContentArg instanceof SmartFile) { + fileContent = fileContentArg.contentBuffer; + // handle options + if (optionsArg.respectRelative) { + filePath = plugins.path.join(filePath, fileContentArg.path); + } + } else if (Buffer.isBuffer(fileContentArg)) { + fileContent = fileContentArg; + fileEncoding = 'binary'; + } else if (typeof fileContentArg === 'string') { + fileContent = fileContentArg; + } else { + throw new Error('fileContent is neither string nor Smartfile'); + } + await ensureDir(plugins.path.parse(filePath).dir); + plugins.fsExtra.writeFile(filePath, fileContent, { encoding: fileEncoding }, done.resolve); + return await done.promise; +}; diff --git a/ts/fsstream.ts b/ts/fsstream.ts index 16baa05..4d41eca 100644 --- a/ts/fsstream.ts +++ b/ts/fsstream.ts @@ -1,7 +1,7 @@ /* This file contains logic for streaming things from and to the filesystem */ -import * as plugins from './smartfile.plugins.js'; +import * as plugins from './plugins.js'; export const createReadStream = (pathArg: string) => { return plugins.fs.createReadStream(pathArg); @@ -97,7 +97,7 @@ export const waitForFileToBeReadyForStreaming = (filePathArg: string): Promise { const extName = plugins.path.extname(pathArg); diff --git a/ts/memory.ts b/ts/memory.ts index c5b0842..f087689 100644 --- a/ts/memory.ts +++ b/ts/memory.ts @@ -1,4 +1,4 @@ -import * as plugins from './smartfile.plugins.js'; +import * as plugins from './plugins.js'; import { SmartFile } from './classes.smartfile.js'; import * as smartfileFs from './fs.js'; import * as interpreter from './interpreter.js'; diff --git a/ts/smartfile.plugins.ts b/ts/plugins.ts similarity index 100% rename from ts/smartfile.plugins.ts rename to ts/plugins.ts