Compare commits

...

8 Commits

Author SHA1 Message Date
eb65c4e859 11.0.8 2024-04-02 21:37:32 +02:00
a1d6c37f18 fix(core): update 2024-04-02 21:37:31 +02:00
915ad00801 11.0.7 2024-04-02 20:58:34 +02:00
910671bfc6 fix(core): update 2024-04-02 20:58:33 +02:00
ae8835d430 11.0.6 2024-04-02 20:53:03 +02:00
d08cc0f350 fix(core): update 2024-04-02 20:53:02 +02:00
1311039127 update npmextra.json: githost 2024-04-01 21:35:01 +02:00
c267d2f226 update npmextra.json: githost 2024-04-01 19:58:14 +02:00
14 changed files with 176 additions and 106 deletions

View File

@ -10,9 +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."
],
"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.5",
"description": "offers smart ways to work with files in nodejs",
"version": "11.0.8",
"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",

158
readme.md
View File

@ -1,126 +1,114 @@
# SmartFile
> SmartFile offers smart ways to work with files in nodejs.
# @push.rocks/smartfile
> offers smart ways to work with files in nodejs
## Install
To install SmartFile, use npm or Yarn as follows:
```
npm install @push.rocks/smartfile --save
```
Or:
```
yarn add @push.rocks/smartfile
To integrate `@push.rocks/smartfile` into your project, run:
```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.
`@push.rocks/smartfile` provides a robust suite of tools for managing files in Node.js projects using modern TypeScript and ESM syntax. It simplifies numerous file operations such as reading, writing, copying, and streaming files, as well as working with directories and virtual file systems.
### Basic File Operations
### **Key Features and Classes**
For reading and writing files, SmartFile provides synchronous and asynchronous methods. Heres how you can use them:
- **`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.
#### Async Write to File
### **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 { memory } from '@push.rocks/smartfile';
const myData: string = 'Hello, SmartFile!';
// Writing string data to a file asynchronously
memory.toFs(myData, './data/hello.txt');
import { SmartFile, StreamFile, VirtualDirectory, memory, fs as smartFs } from '@push.rocks/smartfile';
```
#### Sync Write to File
### **Reading and Writing Files**
#### Reading Files
Reading a JSON file:
```typescript
import { memory } from '@push.rocks/smartfile';
const myData: string = 'Hello, World!';
// Writing string data to a file synchronously
memory.toFsSync(myData, './data/helloSync.txt');
const myJsonFile: SmartFile = await SmartFile.fromFilePath('./data.json');
const jsonData = JSON.parse(myJsonFile.contents.toString());
console.log(jsonData);
```
### Working with Streams
#### Writing Files
Streaming files to and from the filesystem is made easy with SmartFile. Heres an example:
#### Creating Read and Write Streams
Writing content to a file:
```typescript
import { fsStream } from '@push.rocks/smartfile';
import * as fs from 'fs';
// Creating a read stream
const readStream = fsStream.createReadStream('./data/readme.txt');
// Creating a write stream
const writeStream = fsStream.createWriteStream('./data/copy.txt');
// Piping the read stream to the write stream
readStream.pipe(writeStream);
const filePath: string = './output.txt';
const content: string = 'Hello, SmartFile!';
await memory.toFs(content, filePath);
console.log('File saved successfully.');
```
### Dealing with Virtual Directories
### **Streaming Large Files**
Virtual directories allow you to group and manipulate files as if they were in a filesystem structure without actually writing them to disk.
For large files, `StreamFile` provides a memory-efficient streaming solution:
```typescript
import { VirtualDirectory } from '@push.rocks/smartfile';
import { createReadStream } from 'fs';
(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');
})();
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.');
```
### Advanced File Manipulation
### **Working with Virtual Directories**
SmartFile also allows for more advanced file manipulation techniques through the `SmartFile` class.
`VirtualDirectory` abstracts a collection of files allowing operations to be performed as if they were on disk:
```typescript
import { SmartFile } from '@push.rocks/smartfile';
(async () => {
// Create a SmartFile instance from a file path
const smartFile = await SmartFile.fromFilePath('./data/example.txt');
// Edit the file content
await smartFile.editContentAsString(async (currentContent: string) => {
return currentContent.toUpperCase();
});
// Write the changes back to disk
await smartFile.write();
})();
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.');
```
### Conversion and Interpretation
### **Advanced File Operations**
You can easily convert file contents to objects or interpret file types for further processing:
`@push.rocks/smartfile` simplifies complex file operations, including:
```typescript
import { memory } from '@push.rocks/smartfile';
- Copying directories and files
- Removing files or directories
- Listing files and directories with filters
- Reading file content directly into JavaScript objects
(async () => {
const fileString: string = await fs.promises.readFile('./data/example.json', 'utf8');
const fileObject = memory.toObject(fileString, 'json');
### **Web File Handling**
console.log(fileObject);
// Proceed with the object...
})();
```
Handling files from HTTP requests:
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.
`@push.rocks/smartfile` offers utilities to work with files from web sources, making it simpler to manage downloads and uploads.
## Information on Licensing
### **Comprehensive File Management**
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 dont hold you liable.
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.
## 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.

View File

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

View File

@ -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';

View File

@ -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';

View File

@ -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';

View File

@ -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<void> => {
});
};
/**
* 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;
};

View File

@ -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<v
});
};
class SmartReadStream extends plugins.stream.Readable {
export class SmartReadStream extends plugins.stream.Readable {
private watcher: plugins.fs.FSWatcher | null = null;
private lastReadSize: number = 0;
private endTimeout: NodeJS.Timeout | null = null;

View File

@ -1,4 +1,4 @@
import * as plugins from './smartfile.plugins.js';
import * as plugins from './plugins.js';
import * as fsMod from './fs.js';
import * as fsStreamMod from './fsstream.js';
import * as interpreterMod from './interpreter.js';

View File

@ -1,4 +1,4 @@
import * as plugins from './smartfile.plugins.js';
import * as plugins from './plugins.js';
export let filetype = (pathArg: string): string => {
const extName = plugins.path.extname(pathArg);

View File

@ -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';

View File

@ -3,9 +3,12 @@
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
}
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}