Compare commits

..

17 Commits

Author SHA1 Message Date
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
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
5a9e1b5798 11.0.5 2024-04-01 17:46:40 +02:00
b1ec86ee2d fix(core): update 2024-04-01 17:46:40 +02:00
a1353170f6 update npmextra.json: githost 2024-03-30 21:47:12 +01:00
3ff6de201d 11.0.4 2023-11-24 19:29:00 +01:00
f5c106b2ca fix(core): update 2023-11-24 19:28:59 +01:00
d3c26d0d46 11.0.3 2023-11-24 19:15:41 +01:00
9935fe2d3c fix(core): update 2023-11-24 19:15:41 +01:00
15 changed files with 693 additions and 382 deletions

View File

@ -7,12 +7,36 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"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.2",
"description": "offers smart ways to work with files in nodejs",
"version": "11.0.9",
"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,7 +36,7 @@
},
"homepage": "https://gitlab.com/push.rocks/smartfile#readme",
"dependencies": {
"@push.rocks/lik": "^6.0.5",
"@push.rocks/lik": "^6.0.12",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartfile-interfaces": "^1.0.7",
"@push.rocks/smarthash": "^3.0.4",
@ -34,11 +44,11 @@
"@push.rocks/smartmime": "^1.0.5",
"@push.rocks/smartpath": "^5.0.11",
"@push.rocks/smartpromise": "^4.0.2",
"@push.rocks/smartrequest": "^2.0.20",
"@push.rocks/smartstream": "^3.0.7",
"@types/fs-extra": "^11.0.3",
"@push.rocks/smartrequest": "^2.0.21",
"@push.rocks/smartstream": "^3.0.30",
"@types/fs-extra": "^11.0.4",
"@types/glob": "^8.1.0",
"@types/js-yaml": "^4.0.8",
"@types/js-yaml": "^4.0.9",
"fs-extra": "^11.1.1",
"glob": "^10.3.10",
"js-yaml": "^4.1.0"
@ -46,9 +56,9 @@
"devDependencies": {
"@git.zone/tsbuild": "^2.1.70",
"@git.zone/tsrun": "^1.2.46",
"@git.zone/tstest": "^1.0.81",
"@git.zone/tstest": "^1.0.84",
"@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^20.8.10"
"@types/node": "^20.10.0"
},
"files": [
"ts/**/*",

736
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

135
readme.md
View File

@ -1,49 +1,114 @@
# @push.rocks/smartfile
smart ways to work with files in nodejs
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartfile)
* [gitlab.com (source)](https://gitlab.com/push.rocks/smartfile)
* [github.com (source mirror)](https://github.com/push.rocks/smartfile)
* [docs (typedoc)](https://push.rocks.gitlab.io/smartfile/)
> offers smart ways to work with files in nodejs
## Status for master
## Install
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/smartfile/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/smartfile/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/smartfile)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/smartfile)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/smartfile)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/smartfile)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/smartfile)](https://lossless.cloud)
To integrate `@push.rocks/smartfile` into your project, run:
```bash
npm install @push.rocks/smartfile
```
## Usage
smartfile is an approach of being one tool to handle files in diverse environments.
`@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.
### Smartfile Sections
### **Key Features and Classes**
smartfile thinks in sections:
- **`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.
| section | description |
| ----------- | ---------------------------------------------------------------------------- |
| fs | (object) gets data from fs to somewhere |
| memory | gets data from memory to somewhere |
| remote | gets data from remote locations to somewhere |
| interpreter | (object) handles yaml and json |
| smartfile | (class) a virtual representation of a file, alternative to vinyl file format |
### **Getting Started with ESM and TypeScript**
## Contribution
First, ensure your project supports ESM syntax and TypeScript. Then, begin by importing the desired features from `@push.rocks/smartfile`:
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
```typescript
import { SmartFile, StreamFile, VirtualDirectory, memory, fs as smartFs } from '@push.rocks/smartfile';
```
For further information read the linked docs at the top of this readme.
### **Reading and Writing Files**
## Legal
> MIT licensed | **&copy;** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
#### Reading Files
Reading a JSON file:
```typescript
const myJsonFile: SmartFile = await SmartFile.fromFilePath('./data.json');
const jsonData = JSON.parse(myJsonFile.contents.toString());
console.log(jsonData);
```
#### Writing Files
Writing content to a file:
```typescript
const filePath: string = './output.txt';
const content: string = 'Hello, SmartFile!';
await memory.toFs(content, filePath);
console.log('File saved successfully.');
```
### **Streaming Large Files**
For large files, `StreamFile` provides a memory-efficient streaming solution:
```typescript
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.');
```
### **Working with Virtual Directories**
`VirtualDirectory` abstracts a collection of files allowing operations to be performed as if they were on disk:
```typescript
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.');
```
### **Advanced File Operations**
`@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
### **Web File Handling**
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.
### **Comprehensive File Management**
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.2',
description: 'offers smart ways to work with files in nodejs'
version: '11.0.9',
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';
@ -91,6 +91,12 @@ export class SmartFile extends plugins.smartjson.Smartjson {
});
}
public static async fromUrl (urlArg: string) {
const response = await plugins.smartrequest.getBinary(urlArg);
const smartfile = await SmartFile.fromBuffer(urlArg, response.body);
return smartfile;
}
// ========
// INSTANCE
// ========

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

105
ts/fs.ts
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 =============================
===============================================================*/
@ -392,49 +393,99 @@ export const listFileTree = async (
* Watches for file stability before resolving the promise.
*/
export const waitForFileToBeReady = (filePathArg: string): Promise<void> => {
return new Promise((resolve, reject) => {
let lastSize = -1;
let stableCheckTimeout: NodeJS.Timeout | null = null;
return new Promise(async (resolve, reject) => {
let lastFileSize = -1;
let fileIsStable = false;
const clearStableCheckTimeout = () => {
if (stableCheckTimeout) {
clearTimeout(stableCheckTimeout);
stableCheckTimeout = null;
const checkFileStability = async () => {
let currentFileSize: number;
const deferred = plugins.smartpromise.defer();
plugins.fs.stat(filePathArg, (err, stats) => {
if (err) {
fileIsStable = true;
watcher.close();
reject(err);
return;
}
currentFileSize = stats.size;
deferred.resolve();
});
await deferred.promise;
if (currentFileSize === lastFileSize) {
fileIsStable = true;
await plugins.smartdelay.delayFor(100);
resolve();
}
lastFileSize = currentFileSize;
};
const watcher = plugins.fs.watch(filePathArg, (eventType, filename) => {
if (eventType === 'change') {
plugins.fs.stat(filePathArg, (err, stats) => {
if (err) {
watcher.close();
clearStableCheckTimeout();
reject(err);
return;
}
if (stats.size === lastSize) {
clearStableCheckTimeout();
stableCheckTimeout = setTimeout(() => {
watcher.close();
resolve();
}, 5000); // stability duration
} else {
lastSize = stats.size;
}
});
checkFileStability();
}
});
watcher.on('error', (error) => {
clearStableCheckTimeout();
watcher.close();
reject(error);
});
while (!fileIsStable) {
await checkFileStability();
if (!fileIsStable) {
await plugins.smartdelay.delayFor(5000);
}
}
watcher.close();
});
};
/**
* 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"
]
}