Skip to content

Instantly share code, notes, and snippets.

@Abhinav1217
Last active June 2, 2024 19:04
Show Gist options
  • Save Abhinav1217/f3b51709be893ccf3c141ef8eea2e7a7 to your computer and use it in GitHub Desktop.
Save Abhinav1217/f3b51709be893ccf3c141ef8eea2e7a7 to your computer and use it in GitHub Desktop.
Simple TS/JS utility for file IO
/**
* FileUtils Collection | Abhinav Kulshreshtha | Unlicense
*
* A collection of utility functions for file operations, including reading, writing, and checking file existence.
* These functions are designed to simplify common tasks in Node.js applications. Feel free to use, modify, and distribute
* under the Unlicense.
*
* ## Contents:
* - `fileExists`: Checks if a file exists and creates the directory if it doesn't.
* - `readJsonFromFile`: Reads JSON data from a file and returns it as a string.
* - `writeJsonToFile`: Writes JSON data to a file and returns a success message.
*
*
* ## License:
* This code is licensed under the Unlicense. You are free to use, modify, and distribute this code without any restrictions.
* Read full license at https://unlicense.org/ , You can also get a gist of it at https://en.wikipedia.org/wiki/Unlicense
*/
import * as fs from 'fs';
import { resolve } from 'node:path';
/**
* Checks if a file exists at the specified path and creates the directory if it doesn't exist.
* This function ensures that the directory structure leading up to the file is present,
* creating missing directories along the way.
*
* @param {string} filename - The full path to the file, including the filename and extension.
* @returns {Promise<boolean>} A promise that resolves with `true` if the file exists and `false` otherwise.
* @throws Will throw an error if there are issues accessing the filesystem, such as permission errors.
*/
export function fileExists(filename: string): Promise<boolean> {
// Resolves the absolute path to the directory where the file should be located.
const directory = resolve(__dirname, filename);
// Ensures the directory exists; if not, it attempts to create it.
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true }); // Ensures the entire path is created recursively.
}
// Constructs the absolute path to the file.
const filePath = resolve(directory, filename);
// Returns a new promise that checks if the file exists.
return new Promise((resolve) => {
// Uses fs.access to check for the existence of the file.
fs.access(filePath, fs.constants.F_OK, (err) => {
// If an error occurs, it indicates the file does not exist.
if (err) {
resolve(false);
} else {
// If no error, the file exists.
resolve(true);
}
});
});
}
/**
* Reads JSON content from a file and returns it as a string.
*
* @param {string} filename - The name of the file to read from.
* @returns {Promise<string>} A promise that resolves with the contents of the file as a string.
* @throws Will throw an error if the file cannot be read due to issues like file not found or permission errors.
*/
export function readJsonFromFile(filename: string): Promise<string> {
// Resolves the path to the file relative to the current directory (__dirname).
const filePath = resolve(__dirname, filename);
// Returns a new promise that will either resolve with the file's contents or reject with an error message.
return new Promise((resolve, reject) => {
// Attempts to read the file synchronously using Node.js's built-in readFile method.
fs.readFile(filePath, 'utf8', (err, data) => {
// If an error occurs during the read operation, the promise is rejected with an error message.
if (err) {
reject(`Error reading Data from file: ${err}`);
} else {
// If the file is successfully read, the promise is resolved with the file's contents.
resolve(data);
}
});
});
}
/**
* Writes JSON data to a file and returns a promise that resolves with a success message or rejects with an error.
*
* This function takes a file path and JSON data as inputs, writes the JSON data to the specified file, and then resolves the promise with a success message upon successful completion.
* If an error occurs during the write operation, the promise is rejected with an error message detailing the issue.
*
* @param {string} filePath - The full path to the file, including the filename and extension, where the JSON data will be written.
* @param {string} jsonData - The JSON-formatted string to be written to the file.
* @returns {Promise<string>} A promise that resolves with a success message indicating the JSON data has been successfully written to the file, or rejects with an error message if the operation fails.
* @throws Will throw an error if there are issues writing to the file, such as permission errors or disk space limitations.
*/
export function writeJsonToFile(
filePath: string,
jsonData: string
): Promise<string> {
return new Promise((resolve, reject) => {
// Writes the JSON data to the specified file.
fs.writeFile(filePath, jsonData, 'utf8', (err) => {
if (err) {
// Rejects the promise with an error message if an error occurs during the write operation.
reject(`Error writing JSON to file: ${err}`);
} else {
// Resolves the promise with a success message if the JSON data is successfully written to the file.
resolve(`JSON data has been successfully written to ${filePath}`);
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment