bowling-analysis-system
Version:
A comprehensive system for analyzing bowling techniques using video processing and metrics calculation
104 lines (91 loc) • 3.13 kB
JavaScript
/**
* File Saver Processor
*
* Saves files to the filesystem
* @module core/processors/FileSaver
*/
const fs = require('fs');
const path = require('path');
const BaseProcessor = require('../BaseProcessor');
/**
* @class FileSaver
* @description Processor for saving data to the filesystem
* @extends BaseProcessor
*/
class FileSaver extends BaseProcessor {
/**
* Create a new FileSaver processor
* @param {Object} config - Processor configuration
* @param {string} config.filePath - Path to the file to write
* @param {string} [config.format='json'] - File format (json or text)
* @param {string} [config.encoding='utf8'] - File encoding
* @param {boolean} [config.createDirectories=true] - Whether to create directories if they don't exist
*/
constructor(config = {}) {
super('fileSaver', config);
this.filePath = config.filePath;
this.format = config.format || 'json';
this.encoding = config.encoding || 'utf8';
this.createDirectories = config.createDirectories !== false;
}
/**
* Process input data
* @param {*} input - Input data to save
* @param {Object} context - Processing context
* @returns {Promise<Object>} Information about the saved file
*/
async process(input, context = {}) {
const filePath = this.filePath ||
context?.pipeline?.options?.output?.filePath ||
context?.pipeline?.options?.outputPath;
if (!filePath) {
throw new Error('No file path specified');
}
try {
// Resolve path (support relative paths)
const resolvedPath = path.isAbsolute(filePath) ?
filePath : path.resolve(process.cwd(), filePath);
// Create directories if needed
if (this.createDirectories) {
const directory = path.dirname(resolvedPath);
await fs.promises.mkdir(directory, { recursive: true });
}
// Handle different formats
let content = input;
// If the file is JSON, stringify it
if (this.format === 'json' || resolvedPath.toLowerCase().endsWith('.json')) {
if (typeof input !== 'string') {
content = JSON.stringify(input, null, 2);
}
}
// Write to file
await fs.promises.writeFile(resolvedPath, content, this.encoding);
return {
path: resolvedPath,
saved: true,
data: input
};
} catch (error) {
throw new Error(`Failed to save file ${filePath}: ${error.message}`);
}
}
/**
* Save a JSON file
* @param {string} filePath - Path to save the JSON file
* @param {Object} data - Data to save
* @returns {Promise<boolean>} Success status
*/
async saveJsonFile(filePath, data) {
try {
// Create instance with file path configuration
const saver = new FileSaver({ filePath, format: 'json' });
// Save the file
await saver.process(data);
return true;
} catch (error) {
console.error(`Error saving JSON file ${filePath}: ${error.message}`);
return false;
}
}
}
module.exports = { FileSaver };