Skip to content

Instantly share code, notes, and snippets.

@theatom06
Last active September 18, 2023 05:39
Show Gist options
  • Save theatom06/45ff6aeabe74d249965e0776dcb14a2f to your computer and use it in GitHub Desktop.
Save theatom06/45ff6aeabe74d249965e0776dcb14a2f to your computer and use it in GitHub Desktop.
A simple and easy node.js file handler that uses the fs/promises library for handling files.

File Class v2.0.0

This is a simple Node.js class for reading and writing files. It was writen in typescript then into javascript by me (atom06) for the nexus project

github || npm (you can use the same to download in yarn/pnpm)

Usage

import File from 'File.js';

const file = new File('test.txt');

file.init()

// Write data to the file
const [writeSuccess, writeError] = await file.write('Hello, world!');

if (writeSuccess) {
  console.log('Data written to file successfully.');
} else {
  console.error('Error writing to file:', writeError);
}

// Append data to the file
const [appendSuccess, appendError] = await file.append('New data to append.');

if (appendSuccess) {
  console.log('Data appended to file successfully.');
} else {
  console.error('Error appending to file:', appendError);
}

// Read data from the file
const [readSuccess, data] = await file.read();

if (readSuccess) {
  console.log('File data:', data);
} else {
  console.error('Error reading file:', data);
}

API

new File(fileName): File

Create a new File instance with the given file name opening that file.

file.write(data: string): Promise<[boolean, string | unknown]>

Write data to the file. Returns a promise that resolves to a tuple containing a boolean indicating success (true) or failure (false) and either undefined (if successful) or an error object (if failed).

file.read(): Promise<[boolean, string | unknown]>

Read the contents of the file. Returns a promise that resolves to a tuple containing a boolean indicating success (true) or failure (false) and either the contents of the file (if successful) or an error object (if failed).

file.append(data: string): Promise<[boolean, string | unknown]>

Append data to the end of the file. Returns a promise that resolves to a tuple containing a boolean indicating success (true) or failure (false) and either undefined (if successful) or an error object (if failed).

License

This code is licensed which allows for free use and modification as long as the original author (Atom06) is credited and the license is included in all versions of the code and the code is not sublicensed or/and sold.

Upcoming features

  • Reading directorys (Before June 1st)
  • Temporary cache when reading, writing and appending to files improving speed (After May)
import fs from 'fs/promises';
/**
* A class for reading, writing, and appending data to a file.
*/
class FileJS {
/**
* The name of the file to read, write, or append to.
*/
private fileName: string;
/**
* The encoding to use when reading, writing, or appending to the file.
*/
private encoding: BufferEncoding;
/**
* Creates a new instance of the FileJS class.
* @param fileName The name of the file to read, write, or append to.
* @param encoding The encoding to use when reading, writing, or appending to the file.
*/
constructor(fileName: string, encoding: BufferEncoding = 'utf8') {
this.fileName = fileName;
this.encoding = encoding;
}
/**
* Writes data to the file.
* @param data The data to write to the file.
* @returns A Promise that resolves to a tuple containing a boolean indicating whether the write was successful, and an error message if it failed.
*/
async write(data: string): Promise<[boolean, string | null]> {
try {
await fs.writeFile(this.fileName, data, { encoding: this.encoding });
return [true, null];
} catch (error: any) {
return [false, error.message];
}
}
/**
* Reads data from the file.
* @returns A Promise that resolves to a tuple containing a boolean indicating whether the read was successful, and the data read from the file or an error message if it failed.
*/
async read(): Promise<[boolean, string | null]> {
try {
const data = await fs.readFile(this.fileName, this.encoding);
return [true, data.toString()];
} catch (error: any) {
return [false, error.message];
}
}
/**
* Appends data to the file.
* @param data The data to append to the file.
* @returns A Promise that resolves to a tuple containing a boolean indicating whether the append was successful, and an error message if it failed.
*/
async append(data: string): Promise<[boolean, string | null]> {
try {
await fs.appendFile(this.fileName, data, { encoding: this.encoding });
return [true, null];
} catch (error: any) {
return [false, error.message];
}
}
}
export default FileJS;
# Carbon License
_v2.1.0_
Permission is hereby granted, free of charge, to any person or organization (the "**Licensee**") obtaining a copy of software code or project (the "Software") developed by **Steve Louies Alappat**, also known as "Gandalf" or u5106 or just 5106, to use, modify, experiment, test, audit, and learn from the Software, **subject to the following conditions**:
1. **Open Source Use and Non Profits**: If the Licensee incorporates the Software into an **open-source project**, it is required to prominently **acknowledge Steve Louies Alappat** (u5106, 5106 or gandalf) **as the original author** of the Software. The acknowledgment should clearly state **how the Software was utilized**.
2. **Closed Source and Commercial Projects**: Prior to utilizing the Software in closed-source or commercial projects, **written permission must be obtained** from Steve Louies Alappat (u5106, 5106 or gandalf). **The permission from Steve louies Alappat must be in a physical written form.**
3. The permission to use the Software in **closed source and commercial project may involve financial considerations or conditions**, and such terms shall be at the **sole discretion of Steve Louies Alappat (u5106, 5106 or gandalf)**.
The Software **will not be sold to any party** at any price, but **paid usage may be made available** at the **discretion of Steve Louies Alappat** (u5106, 5106 or gandalf).
THE SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL STEVE LOUIES ALAPPAT (CARBON or ATOM06) BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "@atom06/file",
"version": "2.0.0",
"description": "A simple file api to make working with files easier",
"main": "out/file.js",
"type": "module",
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "git+https://gist.github.com/45ff6aeabe74d249965e0776dcb14a2f.git"
},
"keywords": [
"file",
"ts",
"atom06"
],
"author": "Gandalf",
"license": "SEE LICENSE IN license",
"bugs": {
"url": "https://gist.github.com/45ff6aeabe74d249965e0776dcb14a2f"
},
"homepage": "https://gist.github.com/45ff6aeabe74d249965e0776dcb14a2f",
"types": "out/file.d.ts",
"devDependencies": {
"@types/node": "^18.16.3",
"typescript": "^5.0.4"
}
}
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "out",
"declaration": true,
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"types": ["node"],
},
}
@theatom06
Copy link
Author

v1.1.2
readme update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment