Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const PDFMerger = require('pdf-merger-js');
- const axios = require('axios');
- const axiosRetry = require('axios-retry');
- const fs = require('fs');
- const path = require('path');
- const rfs = require('rotating-file-stream');
- const yargs = require('yargs/yargs');
- const { hideBin } = require('yargs/helpers');
- const validateInterval = (interval) => {
- const validUnits = ['s', 'm', 'h', 'd', 'w', 'M', 'y'];
- const unit = interval.slice(-1);
- const number = interval.slice(0, -1);
- if (!validUnits.includes(unit) || isNaN(Number(number))) {
- throw new Error(`Invalid log rotation interval: ${interval}. Must be a number followed by one of 's', 'm', 'h', 'd', 'w', 'M', 'y'.`);
- }
- };
- const argv = yargs(hideBin(process.argv))
- .option('logDirectory', {
- alias: 'd',
- type: 'string',
- description: 'Directory for log files',
- default: path.join(__dirname, 'log'),
- coerce: (arg) => {
- const resolvedPath = path.resolve(arg);
- if (!fs.existsSync(resolvedPath)) {
- fs.mkdirSync(resolvedPath, { recursive: true });
- } else if (!fs.statSync(resolvedPath).isDirectory()) {
- throw new Error(`Invalid log directory: ${resolvedPath} is not a directory.`);
- }
- return resolvedPath;
- },
- })
- .option('logRotationInterval', {
- alias: 'i',
- type: 'string',
- description: 'Log rotation interval',
- default: '1d',
- coerce: (arg) => {
- validateInterval(arg);
- return arg;
- },
- })
- .option('outputFilePath', {
- alias: 'o',
- type: 'string',
- description: 'Path to save the merged PDF',
- default: path.join(__dirname, 'merged.pdf'),
- })
- .option('apiEndpoint', {
- alias: 'e',
- type: 'string',
- description: 'API endpoint to fetch template PDFs',
- default: 'http://localhost:5000/api/upload',
- })
- .option('retryCount', {
- alias: 'r',
- type: 'number',
- description: 'Number of retry attempts for network requests',
- default: 3,
- })
- .option('retryDelay', {
- alias: 't',
- type: 'number',
- description: 'Delay between retry attempts in milliseconds',
- default: 1000,
- })
- .check((argv) => {
- validateInterval(argv.logRotationInterval);
- if (isNaN(argv.retryCount) || argv.retryCount < 0) {
- throw new Error(`Invalid retry count: ${argv.retryCount}. Must be a non-negative number.`);
- }
- if (isNaN(argv.retryDelay) || argv.retryDelay < 0) {
- throw new Error(`Invalid retry delay: ${argv.retryDelay}. Must be a non-negative number.`);
- }
- return true;
- })
- .argv;
- const config = {
- logDirectory: argv.logDirectory,
- logRotationInterval: argv.logRotationInterval,
- outputFilePath: argv.outputFilePath,
- apiEndpoint: argv.apiEndpoint,
- retryCount: argv.retryCount,
- retryDelay: argv.retryDelay,
- };
- const logStream = rfs.createStream('app.log', {
- interval: config.logRotationInterval,
- path: config.logDirectory,
- });
- const log = (message) => {
- const logMessage = `${new Date().toISOString()} - ${message}\n`;
- logStream.write(logMessage);
- console.log(message);
- };
- axiosRetry(axios, {
- retries: config.retryCount,
- retryDelay: (retryCount) => {
- return config.retryDelay * Math.pow(2, retryCount);
- },
- });
- const fetchPdfByName = async (templateName) => {
- try {
- const response = await axios.get(`${config.apiEndpoint}/${templateName}.pdf`, { responseType: 'arraybuffer' });
- return Buffer.from(response.data);
- } catch (error) {
- const errorMessage = `Error fetching PDF "${templateName}": ${error.message}`;
- log(errorMessage);
- if (error.response) {
- log(`Response status: ${error.response.status}`);
- log(`Response data: ${error.response.data}`);
- }
- throw error;
- }
- };
- const mergePdfs = async (userPdfFilePath, templateName) => {
- const merger = new PDFMerger();
- const tempTemplatePath = path.join(__dirname, 'tempTemplate.pdf');
- try {
- await merger.add(userPdfFilePath);
- log(`Added user PDF: ${userPdfFilePath}`);
- const templatePdfBuffer = await fetchPdfByName(templateName);
- fs.writeFileSync(tempTemplatePath, templatePdfBuffer);
- await merger.add(tempTemplatePath);
- log(`Added template PDF: ${templateName}`);
- await merger.save(config.outputFilePath);
- log(`PDFs merged successfully: ${config.outputFilePath}`);
- } catch (error) {
- log(`Error merging PDFs: ${error.message}`);
- if (fs.existsSync(tempTemplatePath)) {
- fs.unlinkSync(tempTemplatePath);
- log(`Temporary template PDF deleted due to error: ${tempTemplatePath}`);
- }
- throw error;
- } finally {
- if (fs.existsSync(tempTemplatePath)) {
- fs.unlinkSync(tempTemplatePath);
- log(`Temporary template PDF deleted: ${tempTemplatePath}`);
- }
- }
- };
- mergePdfs('path/to/user/pdf.pdf', 'templateName').catch((error) => {
- log(`Merge process failed: ${error.message}`);
- });
- // Usage: node script.js --logDirectory=/path/to/log --logRotationInterval=1h --outputFilePath=/path/to/merged.pdf --apiEndpoint=http://example.com/api/upload --retryCount=5 --retryDelay=2000
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement