Files
internetlab-test-task/backend/src/storage/file-storage.service.ts
2026-06-22 09:31:44 +03:00

25 lines
637 B
TypeScript

import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class FileStorageService {
read<T>(filepath: string): T | null {
try {
if (!fs.existsSync(filepath)) return null;
const content = fs.readFileSync(filepath, 'utf-8');
return JSON.parse(content) as T;
} catch {
return null;
}
}
write<T>(filepath: string, data: T): void {
const dir = path.dirname(filepath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(filepath, JSON.stringify(data, null, 2), 'utf-8');
}
}