25 lines
637 B
TypeScript
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');
|
|
}
|
|
}
|