Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const pdfMerge = require('pdf-merge');
- const async = require('async');
- const path = require('path');
- fs.readFile('./config.json', 'utf8', function(err, config) {
- if (err) {
- throw new Error('Eror while loading config file');
- }
- config = JSON.parse(config.replace(/\\/g, '/'));
- if (config.TRANSFLO_DIR[config.TRANSFLO_DIR.length - 1] !== '/' && config.TRANSFLO_DIR) {
- config.TRANSFLO_DIR += '/';
- }
- if (config.INVOICES_DIR[config.INVOICES_DIR.length - 1] !== '/' && config.INVOICES_DIR) {
- config.INVOICES_DIR += '/';
- }
- if (config.RATE_CONFIRMATION_DIR[config.RATE_CONFIRMATION_DIR.length - 1] !== '/' && config.RATE_CONFIRMATION_DIR) {
- config.RATE_CONFIRMATION_DIR += '/';
- }
- const TRANSFLO_DIR = config.TRANSFLO_DIR || './files/TRANSFLO/';
- const INVOICES_DIR = config.INVOICES_DIR || './files/INVOICES/';
- const RATE_DIR = config.RATE_CONFIRMATION_DIR || './files/RATE CONFIRMATIONS/';
- async.parallel([
- function(done) {
- fs.readdir(TRANSFLO_DIR, function(err, files) {
- if (err) {
- throw new Error('Can\'t find TRANSFLO directory');
- }
- done(null, files);
- });
- },
- function(done) {
- fs.readdir(INVOICES_DIR, function(err, files) {
- if (err) {
- throw new Error('Can\'t find INVOICES directory');
- }
- done(null, files);
- });
- },
- function(done) {
- fs.readdir(RATE_DIR, function(err, files) {
- if (err) {
- throw new Error('Can\'t find RATE CONFIRMATIONS directory');
- }
- done(null, files);
- });
- }
- ], function(err, results) {
- if (err) {
- throw new Error('An unknown error has occurred');
- }
- const pairs = [];
- results[0].forEach(function(factor) {
- const match = { factor: TRANSFLO_DIR + factor };
- factor = factor.substr(0, factor.length - 4);
- results[1].forEach(function(invoice) {
- if (invoice.indexOf(factor) !== -1) {
- match.invoice = INVOICES_DIR + invoice;
- }
- });
- results[2].forEach(function(rate) {
- if (rate.indexOf(factor) !== -1) {
- match.rate = RATE_DIR + rate;
- }
- });
- if (match.factor && match.invoice && match.rate) {
- match.label = factor;
- pairs.push(match);
- }
- });
- async.each(pairs, function(pair, done) {
- const paths = [ normalize(pair.invoice), normalize(pair.rate), normalize(pair.factor) ];
- const pdf = new pdfMerge(paths);
- pdf.merge(function(err, result) {
- if (err) {
- throw new Error('An error has occurred while merging the PDF');
- }
- fs.writeFile('./output/' + pair.label + '.pdf', result, function(err) {
- if (err) {
- throw new Error('An error has occurred while saving the PDF');
- }
- done();
- });
- });
- }, function() {
- console.log('All PDFs has been merged successfuly.');
- process.exit();
- });
- }
- );
- })
- const normalize = function(string) {
- return '"' + string + '"';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement