UNPKG

file-converter-nodejs

Version:

A powerful Node.js package for converting files between various formats, splitting and merging files, and automating complex file operations. Backed by LibreOffice and Python, this tool makes file processing seamless for developers.

165 lines (164 loc) 8.76 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileProcessor = void 0; const child_process_1 = require("child_process"); const types_1 = require("./types"); const debug_1 = __importDefault(require("../utils/debug")); const preprocessors_1 = require("./preprocessors"); const path_1 = __importDefault(require("path")); const file_1 = require("../utils/file"); const conversion_config_1 = require("./conversion.config"); class FileProcessor { constructor(globalConfig) { this.runSofficeCommand = (command) => { try { const { libreOfficePath } = this.globalConfig; (0, debug_1.default)(`Running soffice command: $ ${libreOfficePath} ${command}`); const output = (0, child_process_1.execSync)(`${libreOfficePath} ${command}`, { encoding: 'utf-8', stdio: 'ignore', }); (0, debug_1.default)('Conversion output:', output); } catch (error) { throw new Error(`soffice Error: ${error}`); } }; this.handleProcessor = (params, prevProcessorOutput, processor) => __awaiter(this, void 0, void 0, function* () { const { outdir, filePath, from, to } = params; switch (processor.type) { case 'pdf-split': return this.pythonProcessor.handleSplitPdf(filePath, outdir); case 'pptx-split': return this.pythonProcessor.handleSplitPptx(filePath, outdir); case 'merge-docx': return this.pythonProcessor.handleMergeDocx(prevProcessorOutput, path_1.default.join(outdir, `${path_1.default.basename(filePath, path_1.default.extname(filePath))}.${to}`)); case 'merge-pdf': return this.pythonProcessor.handleMergePdf(prevProcessorOutput, path_1.default.join(outdir, `${path_1.default.basename(filePath, path_1.default.extname(filePath))}.${to}`)); case 'merge-pptx': return this.pythonProcessor.handleMergePptx(prevProcessorOutput, path_1.default.join(outdir, `${path_1.default.basename(filePath, path_1.default.extname(filePath))}.${to}`)); case 'convert-each': return prevProcessorOutput.map((filePath) => this.handleSingleConversion({ filePath, from, to, outdir, }, processor, true)); case 'clean-up': (0, preprocessors_1.handleCleanup)(prevProcessorOutput); return prevProcessorOutput; default: throw new Error(`Invalid processor type: ${processor.type}`); } }); this.handleMultiConversion = (params, processorArgs) => __awaiter(this, void 0, void 0, function* () { const { processors } = processorArgs; let prevProcessorOutput = null; for (const processor of processors) { prevProcessorOutput = yield this.handleProcessor(params, prevProcessorOutput, processor); } }); this.handleSingleConversion = (params, conversionArgs, cleanup = false) => { const { outdir, filePath, to } = params; const { filter, infilter } = conversionArgs; const filterArg = filter ? `:${filter}` : ''; const infilterArg = infilter ? `--infilter="${infilter}"` : ''; const command = `${infilterArg} --headless --convert-to ${to}${filterArg} "${filePath}" --outdir ${outdir}`; (0, debug_1.default)(`Converting ${filePath} to ${to}`); this.runSofficeCommand(command); cleanup && (0, preprocessors_1.handleCleanup)(filePath); return path_1.default.join(outdir, `${path_1.default.basename(filePath, path_1.default.extname(filePath))}.${to}`); }; /** * Converts a file from one format to another * * @param params - The parameters for the file conversion * @param params.from - The format of the input file * @param params.to - The format to convert the file to * @param params.outdir - The output directory for the converted file * @param params.filePath - The path to the input file * @returns void */ this.convertFile = (params) => __awaiter(this, void 0, void 0, function* () { const { from, to, outdir, filePath } = params; const parsedParams = Object.assign(Object.assign({}, params), { outdir: outdir !== null && outdir !== void 0 ? outdir : path_1.default.dirname(filePath) }); (0, file_1.validateFilesExist)(filePath); const conversionSettings = (0, conversion_config_1.getConversionSettings)(from, to); if ((0, types_1.isMultiProcessorArgs)(conversionSettings)) { yield this.handleMultiConversion(parsedParams, conversionSettings); } else { this.handleSingleConversion(parsedParams, conversionSettings); } }); /** * Merges multiple files into a single file * * @param params - The parameters for the file merge * @param params.filePaths - The paths to the files to merge * @param params.fileType - The type of the files to merge * @param params.outputFilePath - The path to the output file * @returns void */ this.mergeFiles = (params) => { const filePaths = (0, file_1.findMatchingFiles)(Array.isArray(params.filePaths) ? params.filePaths : [params.filePaths]); if (!filePaths.length) { throw new Error('No files found to merge'); } const { fileType, outputFilePath } = params; switch (fileType) { case 'pdf': this.pythonProcessor.handleMergePdf(filePaths, outputFilePath); break; case 'docx': this.pythonProcessor.handleMergeDocx(filePaths, outputFilePath); break; case 'pptx': this.pythonProcessor.handleMergePptx(filePaths, outputFilePath); break; default: throw new Error(`Invalid file type: ${fileType}`); } }; /** * Splits a file into multiple files * * @param params - The parameters for the file split * @param params.filePath - The path to the file to split * @param params.fileType - The type of the file to split * @param params.outputDir - The output directory for the split files * @returns string[] - Array of all the generated file paths */ this.splitFile = (params) => { const { fileType, outputDir, filePath } = params; (0, file_1.validateFilesExist)(filePath); switch (fileType) { case 'pdf': return this.pythonProcessor.handleSplitPdf(filePath, outputDir); case 'pptx': return this.pythonProcessor.handleSplitPptx(filePath, outputDir); default: throw new Error(`Invalid file type: ${fileType}`); } }; const { libreOfficePath, pythonPath } = globalConfig || {}; this.globalConfig = { libreOfficePath: libreOfficePath !== null && libreOfficePath !== void 0 ? libreOfficePath : 'soffice', pythonPath: pythonPath !== null && pythonPath !== void 0 ? pythonPath : 'python3', }; this.pythonProcessor = new preprocessors_1.PythonProcessor(this.globalConfig.pythonPath); } } exports.FileProcessor = FileProcessor;