Compare commits

..

14 Commits

Author SHA1 Message Date
21b3870a7d 11.0.14 2024-04-14 13:17:47 +02:00
023e1cdf29 fix(core): update 2024-04-14 13:17:46 +02:00
493a235065 11.0.13 2024-04-12 15:00:56 +02:00
e4e48dc9db fix(core): update 2024-04-12 15:00:55 +02:00
7de647daa1 11.0.12 2024-04-12 14:51:23 +02:00
34bc92137b fix(core): update 2024-04-12 14:51:23 +02:00
954df5a0ee 11.0.11 2024-04-12 14:44:13 +02:00
b9c15b11ad fix(core): update 2024-04-12 14:44:12 +02:00
55e6e81957 11.0.10 2024-04-03 15:39:27 +02:00
f37956270c fix(core): update 2024-04-03 15:39:26 +02:00
0c985b9c00 11.0.9 2024-04-03 15:38:59 +02:00
85ff487809 fix(core): update 2024-04-03 15:38:58 +02:00
eb65c4e859 11.0.8 2024-04-02 21:37:32 +02:00
a1d6c37f18 fix(core): update 2024-04-02 21:37:31 +02:00
7 changed files with 947 additions and 1739 deletions

View File

@ -10,14 +10,33 @@
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartfile",
"description": "smart ways to work with files in nodejs",
"description": "provides a robust suite of tools for managing files in Node.js using TypeScript.",
"npmPackagename": "@push.rocks/smartfile",
"license": "MIT"
"license": "MIT",
"keywords": [
"files management",
"TypeScript",
"Node.js",
"read files",
"write files",
"copy files",
"file streaming",
"directories manipulation",
"virtual file system",
"filesystem utilities",
"ESM syntax",
"memory-efficient streaming"
]
}
},
"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."],
"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"
}
}

View File

@ -1,8 +1,8 @@
{
"name": "@push.rocks/smartfile",
"private": false,
"version": "11.0.7",
"description": "offers smart ways to work with files in nodejs",
"version": "11.0.14",
"description": "provides a robust suite of tools for managing files in Node.js using TypeScript.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@ -16,8 +16,18 @@
"url": "git+https://gitlab.com/push.rocks/smartfile.git"
},
"keywords": [
"filesystem",
"json"
"files management",
"TypeScript",
"Node.js",
"read files",
"write files",
"copy files",
"file streaming",
"directories manipulation",
"virtual file system",
"filesystem utilities",
"ESM syntax",
"memory-efficient streaming"
],
"author": "Lossless GmbH <hello@lossless.com> (https://lossless.com)",
"license": "MIT",
@ -26,29 +36,29 @@
},
"homepage": "https://gitlab.com/push.rocks/smartfile#readme",
"dependencies": {
"@push.rocks/lik": "^6.0.12",
"@push.rocks/lik": "^6.0.14",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartfile-interfaces": "^1.0.7",
"@push.rocks/smarthash": "^3.0.4",
"@push.rocks/smartjson": "^5.0.10",
"@push.rocks/smartjson": "^5.0.16",
"@push.rocks/smartmime": "^1.0.5",
"@push.rocks/smartpath": "^5.0.11",
"@push.rocks/smartpath": "^5.0.13",
"@push.rocks/smartpromise": "^4.0.2",
"@push.rocks/smartrequest": "^2.0.21",
"@push.rocks/smartstream": "^3.0.30",
"@push.rocks/smartstream": "^3.0.34",
"@types/fs-extra": "^11.0.4",
"@types/glob": "^8.1.0",
"@types/js-yaml": "^4.0.9",
"fs-extra": "^11.1.1",
"glob": "^10.3.10",
"fs-extra": "^11.2.0",
"glob": "^10.3.12",
"js-yaml": "^4.1.0"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.1.70",
"@git.zone/tsbuild": "^2.1.72",
"@git.zone/tsrun": "^1.2.46",
"@git.zone/tstest": "^1.0.84",
"@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^20.10.0"
"@git.zone/tstest": "^1.0.88",
"@push.rocks/tapbundle": "^5.0.22",
"@types/node": "^20.12.7"
},
"files": [
"ts/**/*",

2297
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

312
readme.md
View File

@ -1,10 +1,10 @@
# @push.rocks/smartfile
> offers smart ways to work with files in nodejs
> Provides a robust suite of tools for managing files in Node.js using TypeScript.
## Install
To install `@push.rocks/smartfile`, run the following command in your project directory:
To integrate `@push.rocks/smartfile` into your project, run:
```bash
npm install @push.rocks/smartfile
@ -12,148 +12,252 @@ npm install @push.rocks/smartfile
## Usage
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.
`@push.rocks/smartfile` offers a comprehensive set of utilities for handling files in Node.js projects using modern TypeScript and ESM syntax. It simplifies various file operations such as reading, writing, copying, and streaming files, as well as working with directories and virtual file systems.
### Working with Filesystem
### Key Features and Classes
#### Ensuring File and Directory Existence
- **`SmartFile`**: Facilitates reading from and writing to individual files, managing metadata.
- **`StreamFile`**: Optimizes memory usage by enabling efficient file streaming.
- **`VirtualDirectory`**: Allows manipulation of a group of files or directories as a virtual file system.
### Getting Started with ESM and TypeScript
First, ensure your project supports ESM syntax and TypeScript. Then, begin by importing the desired features from `@push.rocks/smartfile`:
```typescript
import { fs } from '@push.rocks/smartfile';
// Ensure a file exists with initial content (Async)
await fs.ensureFile('./path/to/new/file.txt', 'Initial content');
// Ensure a directory exists (Async)
await fs.ensureDir('./path/to/new/dir');
```
#### Getting File Details
```typescript
import { fs } from '@push.rocks/smartfile';
// Check if a file exists (Async)
const exists: boolean = await fs.fileExists('./path/to/file.txt');
// Check if a path is a directory
const isDir: boolean = fs.isDirectory('./path/to/check');
import { SmartFile, StreamFile, VirtualDirectory, memory, fs as smartFs } from '@push.rocks/smartfile';
```
### Reading and Writing Files
#### Basic Reading and Writing
#### Reading Files
Reading a JSON file:
```typescript
import { SmartFile, memory } from '@push.rocks/smartfile';
// Read a file to a SmartFile instance (Async)
const smartFile: SmartFile = await SmartFile.fromFilePath('./path/to/read/file.txt');
// Write SmartFile instance to a new path (Async)
await smartFile.writeToDir('./path/to/target/dir');
// Write text content to a file (Async)
await memory.toFs('Hello SmartFile!', './path/to/output/file.txt');
const myJsonFile: SmartFile = await SmartFile.fromFilePath('./data.json');
const jsonData = JSON.parse(myJsonFile.contents.toString());
console.log(jsonData);
```
#### Working with File Contents
#### Writing Files
Writing content to a file:
```typescript
import { SmartFile } from '@push.rocks/smartfile';
// Creating SmartFile instance from text
const smartFileFromText: SmartFile = await SmartFile.fromString('./path/to/text/file.txt', 'Text content here', 'utf8');
// Reading content from SmartFile instance
const content: string = smartFileFromText.contents.toString();
// Editing content of SmartFile
await smartFileFromText.editContentAsString(async (currentContent: string) => `Modified: ${currentContent}`);
const filePath: string = './output.txt';
const content: string = 'Hello, SmartFile!';
await memory.toFs(content, filePath);
console.log('File saved successfully.');
```
### File Streaming
### Streaming Large Files
For large files, `StreamFile` provides a memory-efficient streaming solution:
```typescript
import { StreamFile } from '@push.rocks/smartfile';
// Creating a StreamFile from a file path (Async)
const streamFile: StreamFile = await StreamFile.fromPath('./path/to/large/file.avi');
// Streaming file content to disk (Async)
await streamFile.writeToDisk('./path/to/target/file.avi');
import { createReadStream } from 'fs';
const sourceStream = createReadStream('./large-video.mp4');
const myStreamFile = await StreamFile.fromStream(sourceStream, 'large-video.mp4');
await myStreamFile.writeToDir('./storage');
console.log('Large file streamed to disk successfully.');
```
#### Utilizing Stream Files from URLs
### Working with Virtual Directories
`VirtualDirectory` abstracts a collection of files allowing operations to be performed as if they were on disk:
```typescript
import { StreamFile } from '@push.rocks/smartfile';
// 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();
const virtualDir = new VirtualDirectory();
virtualDir.addSmartfiles([smartFile1, smartFile2]); // Assuming these are SmartFile instances
await virtualDir.saveToDisk('./virtual-output');
console.log('Virtual directory saved to disk.');
```
### Handling Virtual Directories
### Advanced File Operations
```typescript
import { VirtualDirectory, SmartFile } from '@push.rocks/smartfile';
`@push.rocks/smartfile` simplifies complex file operations, including:
- Copying directories and files
- Removing files or directories
- Listing files and directories with filters
- Reading file content directly into JavaScript objects
// Creating a virtual directory from existing directory on disk (Async)
const virtualDirectory: VirtualDirectory = await VirtualDirectory.fromFsDirPath('./path/to/source/dir');
### Web File Handling
// Adding files to virtual directory
virtualDirectory.addSmartfiles([await SmartFile.fromFilePath('./path/to/extra/file.txt')]);
Handling files from HTTP requests:
`@push.rocks/smartfile` offers utilities to work with files from web sources, making it simpler to manage downloads and uploads.
// Saving virtual directory to disk (Async)
await virtualDirectory.saveToDisk('./path/to/destination/dir');
```
### Comprehensive File Management
#### Manipulating File Paths
Whether you're dealing with local files, directories, or files over the internet, `@push.rocks/smartfile` provides a comprehensive set of tools to streamline your workflow and reduce the complexity of file management in your Node.js projects.
```typescript
import { SmartFile } from '@push.rocks/smartfile';
## API Reference
// 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
```
### `SmartFile` Class
### Security and Hashing
#### Static Methods
```typescript
import { SmartFile } from '@push.rocks/smartfile';
- `SmartFile.fromFilePath(filePath: string, baseArg?: string): Promise<SmartFile>`
- Creates a `SmartFile` instance from a file path.
- `SmartFile.fromBuffer(filePath: string, contentBufferArg: Buffer, baseArg?: string): Promise<SmartFile>`
- Creates a `SmartFile` instance from a `Buffer`.
- `SmartFile.fromString(filePath: string, contentStringArg: string, encodingArg: 'utf8' | 'binary', baseArg?: string): Promise<SmartFile>`
- Creates a `SmartFile` instance from a string.
- `SmartFile.fromFoldedJson(foldedJsonArg: string): Promise<SmartFile>`
- Creates a `SmartFile` instance from a folded JSON string.
- `SmartFile.fromStream(stream: Readable, filePath: string, baseArg?: string): Promise<SmartFile>`
- Creates a `SmartFile` instance from a `Readable` stream.
- `SmartFile.fromUrl(urlArg: string): Promise<SmartFile>`
- Creates a `SmartFile` instance from a URL.
// 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'
```
#### Instance Properties
### Advanced Streaming via `SmartReadStream`
- `path: string`
- The relative path of the file.
- `parsedPath: path.ParsedPath`
- A parsed path object.
- `absolutePath: string`
- The absolute path of the file.
- `absoluteParsedPath: path.ParsedPath`
- A parsed absolute path object.
- `contentBuffer: Buffer`
- The content of the file as a `Buffer`.
- `base: string`
- The current working directory of the file.
- `sync: boolean`
- Indicates whether the file is synced with the disk.
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.
#### Instance Methods
```typescript
import { fsStream } from '@push.rocks/smartfile';
- `setContentsFromString(contentString: string, encodingArg?: 'utf8' | 'binary'): void`
- Sets the contents of the file from a string.
- `write(): Promise<void>`
- Writes the file to disk at its original location.
- `writeToDiskAtPath(filePathArg: string): Promise<void>`
- Writes the file to the specified path on disk.
- `writeToDir(dirPathArg: string): Promise<string>`
- Writes the file to a directory combined with the relative path portion.
- `read(): Promise<void>`
- Reads the file from disk.
- `delete(): Promise<void>`
- Deletes the file from disk at its original location.
- `getHash(typeArg?: 'path' | 'content' | 'all'): Promise<string>`
- Returns a hash of the file based on the specified type.
- `updateFileName(fileNameArg: string): void`
- Updates the file name of the `SmartFile` instance.
- `editContentAsString(editFuncArg: (fileStringArg: string) => Promise<string>): Promise<void>`
- Edits the content of the file as a string using the provided edit function.
- `getStream(): Readable`
- Returns a `Readable` stream from the file's content buffer.
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.');
});
```
### `StreamFile` Class
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.
#### Static Methods
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.
- `StreamFile.fromPath(filePath: string): Promise<StreamFile>`
- Creates a `StreamFile` instance from a file path.
- `StreamFile.fromUrl(url: string): Promise<StreamFile>`
- Creates a `StreamFile` instance from a URL.
- `StreamFile.fromBuffer(buffer: Buffer, relativeFilePath?: string): StreamFile`
- Creates a `StreamFile` instance from a `Buffer`.
- `StreamFile.fromStream(stream: Readable, relativeFilePath?: string, multiUse?: boolean): StreamFile`
- Creates a `StreamFile` instance from a `Readable` stream.
#### Instance Properties
- `relativeFilePath?: string`
- The relative file path of the `StreamFile`.
- `multiUse: boolean`
- Indicates whether the `StreamFile` can be used multiple times.
- `used: boolean`
- Indicates whether the `StreamFile` has been used.
#### Instance Methods
- `createReadStream(): Promise<Readable>`
- Creates a new `Readable` stream from the source.
- `writeToDisk(filePathArg: string): Promise<void>`
- Writes the stream to the disk at the specified path.
- `writeToDir(dirPathArg: string): Promise<void>`
- Writes the stream to a directory combined with the relative path portion.
- `getContentAsBuffer(): Promise<Buffer>`
- Returns the content of the `StreamFile` as a `Buffer`.
- `getContentAsString(formatArg?: 'utf8' | 'binary'): Promise<string>`
- Returns the content of the `StreamFile` as a string.
### `VirtualDirectory` Class
#### Static Methods
- `VirtualDirectory.fromFsDirPath(pathArg: string): Promise<VirtualDirectory>`
- Creates a `VirtualDirectory` instance from a file system directory path.
- `VirtualDirectory.fromVirtualDirTransferableObject(virtualDirTransferableObjectArg: VirtualDirTransferableObject): Promise<VirtualDirectory>`
- Creates a `VirtualDirectory` instance from a `VirtualDirTransferableObject`.
#### Instance Properties
- `smartfileArray: SmartFile[]`
- An array of `SmartFile` instances in the `VirtualDirectory`.
#### Instance Methods
- `addSmartfiles(smartfileArrayArg: SmartFile[]): void`
- Adds an array of `SmartFile` instances to the `VirtualDirectory`.
- `getFileByPath(pathArg: string): Promise<SmartFile | undefined>`
- Retrieves a `SmartFile` instance from the `VirtualDirectory` by its path.
- `toVirtualDirTransferableObject(): Promise<VirtualDirTransferableObject>`
- Converts the `VirtualDirectory` to a `VirtualDirTransferableObject`.
- `saveToDisk(dirArg: string): Promise<void>`
- Saves the `VirtualDirectory` to the disk at the specified directory.
- `shiftToSubdirectory(subDir: string): Promise<VirtualDirectory>`
- Shifts the `VirtualDirectory` to a subdirectory.
- `addVirtualDirectory(virtualDir: VirtualDirectory, newRoot: string): Promise<void>`
- Adds another `VirtualDirectory` to the current `VirtualDirectory` with a new root path.
### `fs` Module
The `fs` module provides various file system utility functions. Some notable functions include:
- `fileExistsSync(filePath: string): boolean`
- Checks if a file exists synchronously.
- `fileExists(filePath: string): Promise<boolean>`
- Checks if a file exists asynchronously.
- `listFoldersSync(pathArg: string, regexFilter?: RegExp): string[]`
- Lists folders in a directory synchronously.
- `listFolders(pathArg: string, regexFilter?: RegExp): Promise<string[]>`
- Lists folders in a directory asynchronously.
- `listFilesSync(pathArg: string, regexFilter?: RegExp): string[]`
- Lists files in a directory synchronously.
- `listFiles(pathArg: string, regexFilter?: RegExp): Promise<string[]>`
- Lists files in a directory asynchronously.
- `listFileTree(dirPathArg: string, miniMatchFilter: string, absolutePathsBool?: boolean): Promise<string[]>`
- Lists a file tree using a minimatch filter.
- `waitForFileToBeReady(filePathArg: string): Promise<void>`
- Waits for a file to be ready (exists and is not empty).
- `toFs(filePathArg: string, fileContentArg: string | Buffer | SmartFile | StreamFile, optionsArg?: { respectRelative?: boolean }): Promise<void>`
- Writes a string, `Buffer`, `SmartFile`, or `StreamFile` to the file system.
### `memory` Module
The `memory` module provides utility functions for working with files in memory. Some notable functions include:
- `toObject(fileStringArg: string, fileTypeArg: string): any`
- Converts a file string to an object based on the file type.
- `toFs(fileContentArg: string | Buffer | SmartFile | StreamFile, filePathArg: string, optionsArg?: IToFsOptions): Promise<void>`
- Writes a string, `Buffer`, `SmartFile`, or `StreamFile` to the file system.
- `toFsSync(fileArg: string, filePathArg: string): void`
- Writes a string to the file system synchronously.
- `smartfileArrayToFs(smartfileArrayArg: SmartFile[], dirArg: string): Promise<void>`
- Writes an array of `SmartFile` instances to the file system.
### `interpreter` Module
The `interpreter` module provides utility functions for interpreting file types and contents. Some notable functions include:
- `filetype(pathArg: string): string`
- Determines the file type based on the file path.
- `objectFile(fileStringArg: string, fileTypeArg: any): any`
- Converts a file string to an object based on the file type.
## License and Legal Information

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartfile',
version: '11.0.7',
description: 'offers smart ways to work with files in nodejs'
version: '11.0.14',
description: 'provides a robust suite of tools for managing files in Node.js using TypeScript.'
}

View File

@ -169,7 +169,9 @@ export class SmartFile extends plugins.smartjson.Smartjson {
* - no argument write to exactly where the file was picked up
*/
public async write() {
await memory.toFs(this.contentBuffer, plugins.path.join(this.base, this.path));
let writePath = plugins.smartpath.transform.makeAbsolute(this.path, this.base);
console.log(`writing to ${writePath}`);
await memory.toFs(this.contentBuffer, writePath);
}
/**

View File

@ -447,8 +447,8 @@ export const waitForFileToBeReady = (filePathArg: string): Promise<void> => {
* @param fileBaseArg
*/
export let toFs = async (
filePathArg: string,
fileContentArg: string | Buffer | SmartFile | StreamFile,
filePathArg: string,
optionsArg: {
respectRelative?: boolean;
} = {}