json-fetchfy
Version:
A lightweight Node.js module to fetch, validate, and manipulate JSON data from various sources seamlessly.
71 lines (61 loc) • 2.4 kB
JavaScript
import { promises, readFileSync } from 'fs';
import path from 'path';
class FileReader {
/**
* Lee el contenido de un archivo y devuelve los datos.
* Si es un archivo .json, devuelve los datos como un objeto.
* @param {string} filePath - Ruta al archivo.
* @returns {Promise<any>} - Contenido del archivo (string para archivos de texto, objeto para JSON).
* @throws {Error} - Error si el archivo no puede ser leído o si hay problemas de formato en JSON.
*/
async readFile(filePath) {
try {
const ext = path.extname(filePath).toLowerCase();
const fileContent = await promises.readFile(filePath, 'utf-8');
if (ext === '.json') {
return this.#parseJson(fileContent, filePath);
}
return fileContent; // Si no es JSON, devolver como texto plano
} catch (error) {
throw new Error(`Error leyendo el archivo ${filePath}: ${error.message}`);
}
}
readFileSync(filePath) {
try {
const ext = path.extname(filePath).toLowerCase();
const fileContent = readFileSync(filePath, 'utf-8');
if (ext === '.json') {
return this.#parseJson(fileContent, filePath);
}
return fileContent; // Si no es JSON, devolver como texto plano
} catch (error) {
throw new Error(`Error leyendo el archivo ${filePath}: ${error.message}`);
}
}
/**
* Método privado para parsear archivos JSON y manejar errores.
* @param {string} content - Contenido del archivo JSON como string.
* @param {string} filePath - Ruta del archivo para referencias de error.
* @returns {Object} - El contenido del archivo parseado como JSON.
* @throws {Error} - Si el archivo JSON tiene errores de formato.
*/
#parseJson(content, filePath) {
try {
return JSON.parse(content);
} catch (error) {
throw new Error(`Error parseando JSON en ${filePath}: ${error.message}`);
}
}
/**
* Detecta el tipo de archivo basado en su extensión.
* @param {string} filePath - Ruta del archivo.
* @returns {string} - Devuelve 'json', 'txt' o 'otro' según la extensión.
*/
detectFileType(filePath) {
const ext = path.extname(filePath).toLowerCase();
if (ext === '.json') return 'json';
if (ext === '.txt') return 'txt';
return 'otro';
}
}
export default new FileReader();