elwerene / libreoffice-convert

MIT License
253 stars 96 forks source link

Needs Promise Wrapper around Example Code for calling 'convert' method #63

Closed justdan23 closed 2 years ago

justdan23 commented 3 years ago

For this code to be reused in a Web Service capacity, the sequencing of the call to 'convert' and it's return callback both need to be managed to prevent premature returning.

      var rWsResultT = {};
      var rWsResult_Convert = await new Promise( (resolve, reject) => {

        var rWsResult_ConvertT = convert(sHtmlContent, 'docx:"Office Open XML Text"', undefined, (err, done) => 
        {
          if( err )
          {
            console.log(`Error converting file: ${err}`);

            rWsResultT['Status'] = 'ERROR';
            rWsResultT['Message'] = err;
            if( err.stack !== undefined )
            {
              rWsResultT['Stack'] = err.stack;
            }
          }
          else
          {
            rWsResultT['Status'] = 'OK';
            rWsResultT['Payload'] = done;
          }

          // Here in done you have pdf file which you can save or transfer in another stream
          //fs.writeFileSync( outputPath, done );

          return resolve( rWsResultT );

        }); // End of convert function

      }); // End of Promise wrapper

A future improvement could be to migrate 'convert' away from callbacks and toward use of Promises where the final Promise is returned from 'convert' and thus use 'await' to control it without needing a wrapper Promise. However, the above code does work effectively to control the open source without modifying it.

G-Ray commented 2 years ago

You can easily retrieve a promisified function with util.promisify() https://nodejs.org/dist/latest-v14.x/docs/api/util.html#util_util_promisify_original.

const util = require('util')
const libre = require('libreoffice-convert');

const convert = util.promisify(libre.convert)