Giter Club home page Giter Club logo

convertapi-node's People

Contributors

anandchowdhary avatar dependabot[bot] avatar jonasjasas avatar kostas-jonauskas avatar laurynas-convertapi avatar sowmyaseshathri avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

convertapi-node's Issues

Update axios version to 1.6.0

Hi, I would like to inform you about the CSRF vulnerability issue in axios.
I would appreciate it if you could update the axios.

Expected Behavior

Axios version used is 1.6.0, to resolve known CSRF vulnerability.

Actual Behavior

Current version used is 0.21.1, which is vulnerable to CSRF: https://security.snyk.io/package/npm/axios/0.21.1.

Thank you in advance.

File parameters not interpreted as files

There is a bug in the library when passing multiple files to the converter. For example, DOCX to Compare conversion takes two files as parameters: File and CompareFile. The File parameter is interpreted as a file and sent to CARA as a file object. My guess is that the CompareFile is sent as a plain string (path to file) rather than the file itself. Conversion results in the following error:

 data: {
      Code: 5008,
      Message: 'Unable to access the file. Call failed with status code 500 (Internal Server Error). Remote file C:/Projects/stuff/Test projects/ConvertAPI NodeJs/file-2.docx'
 }

Code snippet to replicate the issue:

const convertapi = require('convertapi')(secret);
convertapi.convert('compare', {
	File: '/path/to/file-1.docx',
	CompareFile: '/path/to/file-2.docx',
	}, 'docx').then(function(res) {
		console.log(res);
})

Please note that there might be more conversions that accept multiple files as parameters, for example PDF watermark overlay (https://www.convertapi.com/pdf-to-watermark-overlay), so hardcoding the logic based on property name is not a good idea.

Not able to target a directory of files.

I keep getting errors when targeting a directory of files. For example: I want to convert file1.heic file2.heic file3.heic instead of targeting 1 file at a time for conversion. How can I achieve this?

How can we implement error handling on this api

Hello Team,
How can i implement error handling with this api.
because there may be any issue while converting files to pdf like size issue , invalid doc format issue.
please let me know about this

Not installing

When i say npm install convertapi -S it is not installing anything. The directory just has two files. One is index.js and the other is package.json. The index.js has only three lines.

module.exports = {
    salute: global.console.log("Hello, world")
};

Nothing else. So the installation itself not working. How can you expect to pay for convertapi for such useless thing.

Is there a way to pass a file buffer or stream instead of a path?

Instead of:

convertapi.convert('pdf', { File: '/path/to/my_file.docx' })

Coult it be possible to do:

convertapi.convert('pdf', { File: myBuffer })

Same thing with the result.file.save(path) function. Instead of giving it a path it would be great if we could save the file directly to Buffer or Stream without having to write the file to disk.

Otherwise, I have to download the file from storage and then write it to disk just so I can have a file path to pass into the convert function.

I have also tried using a download presigned URL from AWS S3 in place of the path, but that also didn't work and threw an error.

Convert docx file received in formData will respond to 415 error.

Function I Declared

import ConvertAPI from 'convertapi';

const convertAPI = new ConvertAPI('KEY');

export const convertImage = async (
  format: string,
  path: string
): Promise<any> => {
  return await convertAPI
    .convert(format, { File: path })
    .then(function (result) {
      // get converted file url
      console.log('Converted file url: ' + result.file.url);

      // save to file
      return result.file.save('/path/to/save/file.pdf');
    })
    .then(function (file) {
      console.log('File saved: ' + file);
    })
    .catch(function (e) {
      console.error(e.toString());
    });
};

I call as follows.

convertImage('webs', request.body.files.docx.path);

Should filepath not be assigned an absolute path?

Default param issue

Line 39 in src/task.js reads:
const result = Object.assign({}, params, this.defaultParams);

This makes it impossible to override the defaultParams (e.g. StoreFile = true). Is this intended?

I wanted to return the raw data of the converted file and the only way I could get it to work was to reverse the 2nd and 3rd arguments here and then set StoreFile=false in the params I was setting.

Consistent socket hang up errors

Unfortunately the library has become broken, as it seems that any large file will result in a "socket hang up" error. Observe an errored request below.

I think the solution involves setting Axios options around keep-alive. But there is no way to pass Axios options...

Error: socket hang up
<ref *2> Writable {
  _writableState: WritableState {
    objectMode: false,
    highWaterMark: 16384,
    finalCalled: false,
    needDrain: false,
    ending: false,
    ended: false,
    finished: false,
    destroyed: false,
    decodeStrings: true,
    defaultEncoding: 'utf8',
    length: 0,
    writing: false,
    corked: 0,
    sync: true,
    bufferProcessing: false,
    onwrite: [Function: bound onwrite],
    writecb: null,
    writelen: 0,
    afterWriteTickInfo: null,
    buffered: [],
    bufferedIndex: 0,
    allBuffers: true,
    allNoop: true,
    pendingcb: 0,
    constructed: true,
    prefinished: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: true,
    errored: null,
    closed: false,
    closeEmitted: false,
    [Symbol(kOnFinished)]: []
  },
  _events: [Object: null prototype] {
    response: [Function: handleResponse],
    error: [Function: handleRequestError]
  },
  _eventsCount: 2,
  _maxListeners: undefined,
  _options: {
    maxRedirects: 21,
    maxBodyLength: 10485760,
    protocol: 'https:',
    path: '/convert/docx/to/jpg?secret=XXX',
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'ConvertAPI-Node/1.11.2',
      'Content-Length': 52
    },
    agent: undefined,
    agents: { http: undefined, https: undefined },
    auth: undefined,
    hostname: 'v2.convertapi.com',
    port: null,
    nativeProtocols: { 'http:': [Object], 'https:': [Object] },
    pathname: '/convert/docx/to/jpg',
    search: '?secret=XXX'
  },
  _ended: true,
  _ending: true,
  _redirectCount: 0,
  _redirects: [],
  _requestBodyLength: 52,
  _requestBodyBuffers: [
    {
      data: <Buffer 46 69 6c 65 3d 77 75 65 32 79 6c 31 63 6c 30 6f 74 67 64 71 35 70 33 62 71 38 38 30 37 77 31 38 73 70 34 35 77 26 53 74 6f 72 65 46 69 6c 65 3d 74 72 ... 2 more bytes>,
      encoding: undefined
    }
  ],
  _onNativeResponse: [Function (anonymous)],
  _currentRequest: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      response: [Function],
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: true,
    _last: false,
    chunkedEncoding: false,
    shouldKeepAlive: true,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: 52,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'v2.convertapi.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 11,
      connecting: false,
      _hadError: true,
      _parent: null,
      _host: 'v2.convertapi.com',
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: null,
      _requestCert: true,
      _rejectUnauthorized: true,
      timeout: 5000,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(alpncallback)]: null,
      [Symbol(res)]: null,
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 165,
      [Symbol(kHandle)]: null,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: -1,
        _idlePrev: null,
        _idleNext: null,
        _idleStart: 3593,
        _onTimeout: null,
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: true,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 163,
        [Symbol(triggerId)]: 161
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 1,
      [Symbol(kBytesRead)]: 537,
      [Symbol(kBytesWritten)]: 96365,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /convert/docx/to/jpg?secret=XXX HTTP/1.1\r\n' +
      'Accept: application/json\r\n' +
      'Content-Type: application/x-www-form-urlencoded\r\n' +
      'User-Agent: ConvertAPI-Node/1.11.2\r\n' +
      'Content-Length: 52\r\n' +
      'Host: v2.convertapi.com\r\n' +
      'Connection: keep-alive\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype] {},
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: true,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 0,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    joinDuplicateHeaders: undefined,
    path: '/convert/docx/to/jpg?secret=XXX',
    _ended: false,
    res: null,
    aborted: false,
    timeoutCb: [Function: emitRequestTimeout],
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: true,
    host: 'v2.convertapi.com',
    protocol: 'https:',
    _redirectable: [Circular *2],
    [Symbol(kCapture)]: false,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      'user-agent': [Array],
      'content-length': [Array],
      host: [Array]
    },
    [Symbol(errored)]: null,
    [Symbol(kHighWaterMark)]: 16384,
    [Symbol(kRejectNonStandardBodyWrites)]: false,
    [Symbol(kUniqueHeaders)]: null
  },
  _currentUrl: 'https://v2.convertapi.com/convert/docx/to/jpg?secret=XXX',
  [Symbol(kCapture)]: false
}

Server URL overwrite bug

There is an issue with the URL builder. When overwriting the server URL with slash '/' at the end, it results in 404 error:

const convertapi = require('convertapi')(secret, options = { baseUri: 'https://stag-v2.convertapi.com/'});

compare API is returning - Code: 5009, Message: 'File id is not valid.'

compare API is returning - Code: 5009, Message: 'File id is not valid.' with NodeJS

`let http = require('http');
let formidable = require('formidable');
let fs = require('fs');

http.createServer(function (req, res) {

//Create an instance of the form object
let form = new formidable.IncomingForm();

//Process the file upload in Node
form.parse(req, function (error, fields, file) {
let filepath = file.fileupload1.filepath;
let newpath1 = '/path_to_folder/compare-docs/';
newpath1 += file.fileupload1.originalFilename;

//Copy the uploaded file to a custom folder
fs.rename(filepath, newpath1, function () {
    /* will handle later */ 
});

filepath = file.fileupload2.filepath;
let newpath2 = '/path_to_folder/compare-docs/';
newpath2 += file.fileupload2.originalFilename;

//Copy the uploaded file to a custom folder
fs.rename(filepath, newpath2, function () {
    /* will handle later */ 
   // res.write('NodeJS File Upload Success!');
    //res.end();
});
try{
  let convertapi = require('convertapi')('MY API KEY');
    console.log('newpath1: ',newpath1);
    console.log('newpath2: ',newpath2);
  convertapi.convert('compare', {
      File: newpath1,
      CompareFile: newpath2
  }, 'docx').then(function(result) {
      result.saveFiles('/path_to_folder/compare-docs/');
  });
}
catch(e){
  console.log(e);
}
  });
}).listen(800);`

require(...) is not a function

I've been trying to update convertapi from 1.5.0 to 1.10.1 but have been having trouble with it. I am specifically attempting to update to 1.10.1 as it solves an earlier issue I had opened #36

My code is:

const convertapi = require('convertapi')(process.env.CONVERT_API_KEY);

My package.json line is:

"convertapi": "^1.10.1"

and my package.lock has:

    "convertapi": {
      "version": "1.10.1",
      "resolved": "https://registry.npmjs.org/convertapi/-/convertapi-1.10.1.tgz",
      "integrity": "sha512-lReLTolrMC+hbEmcY2MjSsqK9zf2YHnjZLrQMd9HK4dvLwLFs5jzvG42Ps8MyT8qzV8AHIMZNlgoPG2t6AzVtw==",
      "requires": {
        "axios": "^0.21.1"
      }
    },

This code throws the error:

TypeError: require(...) is not a function\n    at /path/to/file.js:145:66

This was not happening in 1.5.0

*I went through each version one by one and it worked up until 1.9.1 and stopped working for 1.10.0

StoreFile is set to true, should be false & normalizeParams should be updated

  1. According to the documentation, this StoreFile param should be set to False:
    this.defaultParams = { StoreFile: true };

    Screen Shot 2021-02-25 at 1 03 54 PM

2)The ordering of the args passed into Object.assign() should be switched to Object.assign({}, this.defaultParams, params)
because the way this code is currently written, this.defaultParams will always be stored over the params that a user passes in

const result = Object.assign({}, params, this.defaultParams);

How to get the file object

Hello there,
I'm not able to find how to get the converted file without saving it locally (I'm working with readOnly environment).
I would like to get the file object and manipulate it without having to save it locally with File.save('path').

Is it possible?

Many thanks,

Not routing through system proxy

I'm trying to use ConvertAPI on Node v12.4.0 behind a corporate proxy but the node library doesn't appear to be following the system default or nodes specific proxy settings.

Is there a way to set a proxy specifically for ConvertAPI library or does this need adding?

I tried to compress api

It will not workout, it throws promise error. May i know how can i use compress api in node js.
Error :
Unhandled Rejection at: Promise Promise {
{ Error: read ECONNRESET

Here is my code :
var convertapi = require('convertapi')('<< Secret Key >>'); //not api secret key

convertapi.convert('compress', {
File: './public/report/report-1.pdf'
}, 'pdf').then(function(result) {
result.saveFiles('./public/report/report-1.pdf');
});

Why I got TypeError: _fs2.default.createReadStream is not a function

When I try to use convertapi convert word to png, I got errors:

index.js:1 TypeError: _fs2.default.createReadStream is not a function

`import ConvertAPI from 'convertapi';

const convertapi = new ConvertAPI(mysecret);
console.log(dataTransfer.files[0]);
convertapi.convert('png', { File: dataTransfer.files[0] })
.then(function (result) {
console.log(result);
})
.catch(function (e) {
console.error(e.toString());
});`

Here is the dataTransfer.files[0]:
image

Server-Side Request Forgery vuln

High โ”‚ Server-Side Request Forgery โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Package โ”‚ axios โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Patched in โ”‚ >=0.21.1 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Dependency of โ”‚ convertapi โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Path โ”‚ convertapi > axios โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ More info โ”‚ https://npmjs.com/advisories/1594

Request body larger than maxBodyLength Limit

I have been getting an error trying to split a large pdf with this library.

Here's my code:

convertapi.convert('split', {
  File: fileName
}, 'pdf')

Here's the error:

{ Error: Request body larger than maxBodyLength limit
    at Function.handleError (/node_modules/convertapi/lib/client.js:1:2396)
    at then.catch.a (/node_modules/convertapi/lib/client.js:1:2231)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

I upgraded to version 1.9.1 and still experience this error

Produces corrupt PDFs

Hey,
I was using your library to convert html to pdf, and sometimes it produces corrupt files. Most probably you're not waiting for a promise somewhere. Please check the code.
I made direct requests to the API and that works well, so I highly suspect the bug is in your code.
Cheers

Request body larger than maxBodyLength limit

Error uploading a large document (24MB) for conversion using convertapi.convert(...)

LOGS:

converting via convertapi...
Error from view function: "merge"
 { Error: Request body larger than maxBodyLength limit
    at Function.handleError (/Users/rohit/dpapp/documerge.io/doc_server/node_modules/convertapi/lib/client.js:15:262)
    at then.catch.a (/Users/rohit/dpapp/documerge.io/doc_server/node_modules/convertapi/lib/client.js:15:97)
    at processTicksAndRejections (internal/process/next_tick.js:81:5) data: null }

I tried adding the following and it works.
image

const options = {

IInvalid structure of a zip file

Is there any possible way to keep the extracted files of a zip file with their structure ?

Ex:

{ "FileName": "Summary.png",
  "FileSize": 11017,
  "FileId": "2bfa1b8f2649d9b54ebd825c20a17721",
  "Url": "https://v2.convertapi.com/d/2bfa1b8f2649d9b54ebd825c20a17721/Summary.png" }

This file should be under another folder but it is not.

Can you guys help me ?

Alternative "Converter" parameter lowercase

When passing the "Converter" parameter starting with the capital "C" the conversion fails:

image

If we pass "converter" instead of "Converter" then it succeeds. The converter matching should ignore the case.

Here is the code to replicate the bug:

async function start() {
	try {
		let secret = '<your secret here>'
		const convertapi = require('convertapi')(secret);
		let result = convertapi.convert('pdf', {
			File: 'path/to/sample.xlsx',
			PageSize: 'envelopeusa',
			Converter: 'Printer'
			}, 'xlsx').then(function(res) {
				console.log(res);
		});
		console.log(result);
	}
	catch(exception) {
		throw exception;
	}
}

start();

How to get output in base64 buffer

I used your API and I found out that in convert-api node module, I don't get base64 buffer from your response but I get base64 buffer response from your URL request ( https://v2.convertapi.com/convert/pdf/to/compress?Secret=** )

In node package, I get compress image in form of your storage URL, but I want base64 buffer.

WHY This type of difference output in URL request and module request?

Can I get formData/base64 Buffer from node package?

Thanks

Error: socket hang up

Users started to get "socket hang up" error. This is what I know:
NodeJS: 20

Error:

,"name":"Error","message":"socket hang up","stack":"Error: socket hang up\n at Client.handleError (/app/node_modules/.pnpm/[email protected]/node_modules/convertapi/lib/client.js:127:11)\n at /app/node_modules/.pnpm/[email protected]/node_modules/convertapi/lib/client.js:62:96"

Code:

do {
try {
return await this.api.convert(toFormat, params, fromFormat, conversionTimeout);
} catch (e: any) {
lastError = e;
tries += 1;
}
} while (tries < this.maxRetries);

Conversion: docx to pdf

Params:

{
"File": "<local filelsystem>/output.docx"
}

File: output.docx

TypeError: convertapi_1.default is not a function

My NodeJS/Typescript code looks like this:

import convertapiPackage from 'convertapi';

...

const convertapi = convertapiPackage('MY_SECRET');
return convertapi
    .convert('pdf', {
        File: url,
    })
    .then(function (result) {
        // stuff here
    })
    .catch(function (e) {
        // stuff here
    });

When I ran than I was getting an error

TypeError: convertapi_1.default is not a function

After reading on some posts online, people had this generic issue:

https://stackoverflow.com/questions/61524130/typescript-babel-import-causing-1-default-is-not-a-function

The recommendation is to update your tsconfig.json file with "esModuleInterop": true

Once I did that, I had to update a bunch of imports in my code, but once I got through that, it worked.

Anyway, why does the convertApi NodeJS SDK enforce us to set "esModuleInterop": true?

Do not pass any TimeOut property to ConvertAPI and set HTTP Client timeout to 1800 seconds

Do not pass any default TimeOut property to ConvertAPI and set HTTP Client timeout to 1800 seconds. The idea is to use the default converter timeout of ConvertAPI if no timeout is set and to prevent HTTP Client request deadlock set default HTTPClient timeout to 1800 seconds.

If, however, timeout is set we handle it as before, pass a timeout to ConvertAPI and set HTTPClient Timeout to: ConvertAPITimeOut+conversion_timeout_delta

conversion_timeout_delta = 10

Review PR for typings in DefinitelyTyped

The DefiniteTyped repository is a perfect place to maintain the types of the library.

I have made a PR to add them here DefinitelyTyped/DefinitelyTyped#50684 @laurynas-baltsoft Could you please review it ? Of course I gave you credits for the update ๐Ÿ‘๐Ÿผ thanks again.

We will be able to do: npm install --save convertapi and npm install --save-dev @types/convertapi after it gets merged.

Feel free to close this issue when you have reviewed it.

Update typings after version 1.18.0

Hello,

Thanks for the recent update of the package.

I have noticed that the convert returns a Promise<Result> but Result does not contain JobId which can be returned when calling convert with the Async flag.

Here's an example:

const response = await client.convert('pdf',
      {
        File: url,
        WebHook: 'my webhook url',
        Async: true,
      }
    )

The output of this response contains a lot of parameters that are not included in Result

here's the log of the previous statement.

 {
  api: { 
    secret: '*******',
    baseUri: 'https://v2.convertapi.com',
    conversionTimeout: undefined,
    conversionTimeoutDelta: 10,
    uploadTimeout: 1800,
    downloadTimeout: 1800,
    userAgent: 'ConvertAPI-Node/1.8.0',
    proxy: undefined,
  },
  response: { JobId: 'SOME-JOB-ID-GOES-HERE' }
}

Could you please support this? Also the location of the index.d.ts is not the correct one, you could put it in the root of the project or in a types folder.

Thanks in advance.

Async Workflow broken

Proof of concept

const convertapi = require('convertapi')(process.env.CONVERT_API_SECRET);

const params = {
  Async: true,
  WebHook: 'https://www.test.com',
  File: 'doc.docx',
};

const run = async () => {
  const result = await convertapi.convert('pdf', params);

  console.log(result);
};

run()
  .then(process.exit)
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });

Output

Result {
  api: <ref *1> {
    secret: 'fc019yGBiN7U85wy',
    baseUri: 'https://v2.convertapi.com',
    conversionTimeout: undefined,
    conversionTimeoutDelta: 10,
    uploadTimeout: 1800,
    downloadTimeout: 1800,
    userAgent: 'ConvertAPI-Node/1.11.0',
    proxy: undefined,
    client: Client { api: [Circular *1], defaultHeader: [Object] }
  },
  response: { ConversionCost: 1, Files: [ [Object] ] }
}

For async processing a JobId should be present in the response object. It is not.

Debugging

Adding console.log(path) here: https://github.com/ConvertAPI/convertapi-node/blob/master/src/task.js#L26

We can see the path is convert/docx/to/pdf

The ConvertAPI documentation for Async processing can be found here: https://www.convertapi.com/doc/async

The key part to note is that the path should be async/convert/docx/to/pdf

The logic in the node client has not changed since May 2021, so I can only assume they've made a breaking change to the API.

TLDR

It looks like the API has changed to include async at the start of the path, but the client has not been update to reflect this. Thus, instead of a JobId being returned in the response object, we get the response we would get for synchronous processing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.