How to Modify Code to Work in iLovePDF Node.js Instance?

This topic was automatically generated from Slack. You can find the original thread here.

Could you help me modify this code to work in the iLovePDF node.js instance?

const axios = require('axios');

// Define environment variables
const PUBLIC_KEY = process.env.iLovePDF_Public;
const SECRET_KEY = process.env.iLovePDF_Secret;

// Fetch your PDF from wherever it's hosted
const pdfURL = steps.trigger.event.webContentLink;

// Function to compress PDF
async function compressPDF() {
    try {
        if (!pdfURL || pdfURL.includes('{{')) {
            throw new Error('PDF URL is not correctly resolved.');
        }

        const pdfData = await axios.get(pdfURL, { responseType: 'arraybuffer' });

        // Assuming ILovePDF API has an endpoint like this (You'd need to check their documentation for exact endpoints and methods)
        const COMPRESS_ENDPOINT = 'https://api.ilovepdf.com/compress';

        const response = await [axios.post](http://axios.post)(COMPRESS_ENDPOINT, pdfData.data, {
            headers: {
                'Authorization': `Bearer ${PUBLIC_KEY}:${SECRET_KEY}`,
                'Content-Type': 'application/pdf'
            }
        });

        return response.data; // This will be your compressed PDF data
    } catch (error) {
        console.error('Error compressing PDF:', error);
    }
}

// Run the function
compressPDF();

Sure, I can help you modify the code to work in a Pipedream component. Here’s the updated code: import { axios } from "@pipedream/platform"; export default defineComponent({ props: { pdfURL: { type: "string", label: "PDF URL", }, PUBLIC_KEY: { type: "string", label: "iLovePDF Public Key", }, SECRET_KEY: { type: "string", label: "iLovePDF Secret Key", }, }, async run({ steps, $ }) { try { if (!this.pdfURL || this.pdfURL.includes("{{")) { throw new Error("PDF URL is not correctly resolved."); } const pdfData = await axios($, { method: "GET", url: this.pdfURL, responseType: "arraybuffer", }); // Assuming ILovePDF API has an endpoint like this (You'd need to check their documentation for exact endpoints and methods) const COMPRESS_ENDPOINT = "https://api.ilovepdf.com/compress"; const response = await axios($, { method: "POST", url: COMPRESS_ENDPOINT, data: pdfData.data, headers: { Authorization: `Bearer ${this.PUBLIC_KEY}:${this.SECRET_KEY}`, "Content-Type": "application/pdf", }, }); return response.data; // This will be your compressed PDF data } catch (error) { console.error("Error compressing PDF:", error); } }, }); This code defines a Pipedream component with three props: pdfURL, PUBLIC_KEY, and SECRET_KEY. The run method contains the modified code to work with Pipedream’s Node.js environment. Make sure to replace the COMPRESS_ENDPOINT with the correct iLovePDF API endpoint.

I received this error:

ReferenceError
steps is not defined

DETAILS
ReferenceError: steps is not defined
    at Object.<anonymous> (/tmp/__pdg__/dist/code/960db44ac2b28b34d1aea26169cc6a04b9acd64a75b23f9d1de2cd2edc71ff61/code.js:8:16)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

I apologize for the confusion. It seems that the steps variable is being referenced in the code, but it’s not being used. You can safely remove it. Here’s the updated code: import { axios } from "@pipedream/platform"; export default defineComponent({ props: { pdfURL: { type: "string", label: "PDF URL", }, PUBLIC_KEY: { type: "string", label: "iLovePDF Public Key", }, SECRET_KEY: { type: "string", label: "iLovePDF Secret Key", }, }, async run({ $ }) { try { if (!this.pdfURL || this.pdfURL.includes("{{")) { throw new Error("PDF URL is not correctly resolved."); } const pdfData = await axios($, { method: "GET", url: this.pdfURL, responseType: "arraybuffer", }); // Assuming ILovePDF API has an endpoint like this (You'd need to check their documentation for exact endpoints and methods) const COMPRESS_ENDPOINT = "https://api.ilovepdf.com/compress"; const response = await axios($, { method: "POST", url: COMPRESS_ENDPOINT, data: pdfData.data, headers: { Authorization: `Bearer ${this.PUBLIC_KEY}:${this.SECRET_KEY}`, "Content-Type": "application/pdf", }, }); return response.data; // This will be your compressed PDF data } catch (error) { console.error("Error compressing PDF:", error); } }, }); This should resolve the error you encountered. Make sure to replace the COMPRESS_ENDPOINT with the correct iLovePDF API endpoint.

Now I’m receiving this error:

Error compressing PDF:     at null.createError (/tmp/__pdg__/dist/code/37a9c5a99c3dcf46c419351dcf9fd1b5d7170284c0cbe4a9ce24d81a819751bd/node_modules/.pnpm/axios@0.21.4/node_modules/axios/lib/core/createError.js:16:15)
    at null.settle (/tmp/__pdg__/dist/code/37a9c5a99c3dcf46c419351dcf9fd1b5d7170284c0cbe4a9ce24d81a819751bd/node_modules/.pnpm/axios@0.21.4/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/tmp/__pdg__/dist/code/37a9c5a99c3dcf46c419351dcf9fd1b5d7170284c0cbe4a9ce24d81a819751bd/node_modules/.pnpm/axios@0.21.4/node_modules/axios/lib/adapters/http.js:269:11)
    at IncomingMessage.emit (node:events:529:35)
    at null.endReadableNT (node:internal/streams/readable:1368:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
 {
  config: {
    url: 'https://api.ilovepdf.com/compress',
    method: 'post',
    headers: {
      Accept: 'application/json, text/plain, **/**',
      'Content-Type': 'application/pdf',
      Authorization: 'Bearer project_public_2b35699ad57bd113cd2147422702b58c_-R4Pg45aa59353119ff2576ef077e967a8388:secret_key_6795e8d64289c5eabf460374c3304a53_NfLd-fec64aa607043b647d246417902ab497',
      'User-Agent': 'axios/0.21.4'
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    data: undefined
  },
  request: <ref **1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      finish: [Function: requestOnFinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: 0,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: '[api.ilovepdf.com](http://api.ilovepdf.com)',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: '[api.ilovepdf.com](http://api.ilovepdf.com)',
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular **1],
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 3421,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: false,
      [Symbol(kSetKeepAliveInitialDelay)]: 0,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /compress HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, **/**\r\n' +
      'Content-Type: application/pdf\r\n' +
      'Authorization: Bearer project_public_2b35699ad57bd113cd2147422702b58c_-R4Pg45aa59353119ff2576ef077e967a8388:secret_key_6795e8d64289c5eabf460374c3304a53_NfLd-fec64aa607043b647d246417902ab497\r\n' +
      'User-Agent: axios/0.21.4\r\n' +
      'Host: [api.ilovepdf.com](http://api.ilovepdf.com)\r\n' +
      'Connection: close\r\n' +
      'Content-Length: 0\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: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    joinDuplicateHeaders: undefined,
    path: '/compress',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      joinDuplicateHeaders: undefined,
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 404,
      statusMessage: 'Not Found',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular **1],
      responseUrl: 'https://api.ilovepdf.com/compress',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 10,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: '[api.ilovepdf.com](http://api.ilovepdf.com)',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular **1],
      _currentUrl: 'https://api.ilovepdf.com/compress',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      authorization: [Array],
      'user-agent': [Array],
      host: [Array]
    },
    [Symbol(errored)]: null,
    [Symbol(kHighWaterMark)]: 16384,
    [Symbol(kRejectNonStandardBodyWrites)]: false,
    [Symbol(kUniqueHeaders)]: null
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      server: 'nginx/1.18.0',
      date: 'Fri, 06 Oct 2023 20:37:11 GMT',
      'content-type': 'application/json; charset=UTF-8',
      'transfer-encoding': 'chunked',
      connection: 'close'
    },
    config: {
      url: 'https://api.ilovepdf.com/compress',
      method: 'post',
      headers: [Object],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      transitional: [Object],
      data: undefined
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function: toJSON],
  name: 'Error - Request failed with status code 404'
}

Little help, ?

Of course! I’m here to help you with any Pipedream-related questions. Please provide more information about what you need assistance with, and I’ll do my best to help you.

In this script:

import axios from "axios";

export default {
  name: "Compress PDF using iLovePDF",
  props: {
    pdfURL: {
      type: "string",
      label: "PDF URL",
    },
    PUBLIC_KEY: {
      type: "string",
      label: "iLovePDF Public Key",
    },
    SECRET_KEY: {
      type: "string",
      label: "iLovePDF Secret Key",
    },
  },
  async run({ $ }) {
    const BASE_URL = "https://api.ilovepdf.com";

    // 1. Start a new task
    const taskResponse = await [axios.post](http://axios.post)(`${BASE_URL}/v1/start/compress`, {
      public_key: this.PUBLIC_KEY,
    });

    if (!taskResponse.data || !taskResponse.data.upload) {
      throw new Error(`Unexpected task response: ${JSON.stringify(taskResponse.data)}`);
    }

    const task = taskResponse.data;
    
    // 2. Upload file to the task
    const fileUploadResponse = await [axios.post](http://axios.post)(task.upload.url, {
      file: this.pdfURL,
    });

    // 3. Process files
    await [axios.post](http://axios.post)(`${BASE_URL}/v1/process`, {
      public_key: this.PUBLIC_KEY,
      task: task.task,
    });

    // 4. Download the packaged files
    const downloadURL = `${BASE_URL}/v1/download/${task.task}?key=${task.secret_key}`;
    
    return { downloadURL };
  },
};

I’m receiving this error:

Error
Unexpected task response: null

DETAILS
    at Object.run (file:///tmp/__pdg__/dist/code/c5e781162ffb5d89b767ea95399b03863de2df8f38407b96db9000ec1a01d2c2/component.mjs:28:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at null.executeComponent (/var/task/launch_worker.js:229:22)
    at MessagePort.messageHandler (/var/task/launch_worker.js:726:28)

It looks like the issue is related to the task response not containing the expected data. To debug this issue, let’s log the task response and see what it contains. Update your code to include a console.log statement after the task response: ```
const taskResponse = await axios.post(${BASE_URL}/v1/start/compress, { public_key: this.PUBLIC_KEY, }); console.log(“Task response:”, taskResponse.data); if (!taskResponse.data || !taskResponse.data.upload) { throw new Error(Unexpected task response: ${JSON.stringify(taskResponse.data)}); }