CloudConvert Node.js SDK

repository·master·Indexed 41 days ago

https://github.com/cloudconvert/cloudconvert-node

Official Node.js SDK for the CloudConvert API v2 (version 3.0.0). Provides a programmatic interface for file conversions, uploads, downloads, and real-time job monitoring. Features include job and task management, WebSocket event subscriptions, webhook signature verification, and signed URL generation.

Tokens
5.8K
Snippets
24
Records
26
Agent score
52%

What's inside CloudConvert

  1. Upload files to CloudConvert

    master

    To upload files, first create a job with an import/upload task. Then, use the cloudConvert.tasks.upload() method to stream the file to that task.

    Note on custom streams: The SDK automatically detects the file size for file-based read streams. If you are using a custom stream where the length is not known, you must pass the fileSize as the fourth parameter to the upload() method.

    const job = await cloudConvert.jobs.create({
        tasks: {
            'upload-my-file': {
                operation: 'import/upload'
            }
            // ...
        }
    });
    
    const uploadTask = job.tasks.find(task => task.name === 'upload-my-file');
    const inputFile = fs.createReadStream('./file.pdf');
    
    await cloudConvert.tasks.upload(uploadTask, inputFile, 'file.pdf');
  2. Download exported files

    master

    When using export/url tasks, CloudConvert generates public URLs for the output files. To download them:

    1. Wait for the job to complete using cloudConvert.jobs.wait(job.id).
    2. Retrieve the export URLs using cloudConvert.jobs.getExportUrls(job).
    3. Use a standard HTTP client (like https.get) to pipe the file to a local write stream.
    job = await cloudConvert.jobs.wait(job.id); // Wait for job completion
    
    const file = this.cloudConvert.jobs.getExportUrls(job)[0];
    
    const writeStream = fs.createWriteStream('./out/' + file.filename);
    
    https.get(file.url, function (response) {
        response.pipe(writeStream);
    });
    
    await new Promise((resolve, reject) => {
        writeStream.on('finish', resolve);
        writeStream.on('error', reject);
    });
  3. Subscribe to Websocket events

    master

    The SDK supports subscribing to real-time events via the CloudConvert socket.io API. You can subscribe to events for an entire job or for specific tasks within a job.

    Available Job Events: created, updated, finished, failed. Available Task Events: created, updated, finished, failed.

    To stop receiving events and close the connection, call cloudConvert.closeSocket().

    const job = await cloudConvert.jobs.create({ ... });
    
    // Events for the job
    cloudConvert.jobs.subscribeEvent(job.id, 'finished', event => {
        // Job has finished
        console.log(event.job);
    });
    
    // Events for all tasks of the job
    cloudConvert.jobs.subscribeTaskEvent(job.id, 'finished', event => {
        // Task has finished
        console.log(event.task);
    });
    
    // Close the socket when done
    cloudConvert.closeSocket();
  4. Verify Webhook signatures

    master

    To ensure webhook requests are legitimately from CloudConvert, use cloudConvert.webhooks.verify(). This method compares the raw request body against the signature provided in the headers.

    const payloadString = '...'; // The JSON string from the raw request body.
    const signature = '...'; // The value of the "CloudConvert-Signature" header.
    const signingSecret = '...'; // You can find it in your webhook settings.
    
    const isValid = cloudConvert.webhooks.verify(
        payloadString,
        signature,
        signingSecret
    ); // returns true or false
  5. Generate Signed URLs

    master

    Signed URLs allow you to perform conversions on-demand using only URL query parameters. To use this, you must obtain a signedUrlBase and a signingSecret from the CloudConvert Dashboard.

    Use cloudConvert.signedUrls.sign() to generate the URL. You can optionally provide a cacheKey to cache the resulting file for 24 hours.

    const signedUrlBase = 'https://s.cloudconvert.com/...';
    const signingSecret = '...';
    const cacheKey = 'cache-key';
    
    const job = {
        tasks: {
            'import-it': {
                operation: 'import/url',
                url: 'https://some.url',
                filename: 'logo.png'
            },
            'export-it': {
                operation: 'export/url',
                input: 'import-it',
                inline: true
            }
        }
    };
    
    const url = cloudConvert.signedUrls.sign(
        signedUrlBase,
        signingSecret,
        job,
        cacheKey
    ); // returns the generated URL
  6. Initialize the CloudConvert client

    master

    Import the CloudConvert class and instantiate it with your API key. You can also optionally enable Sandbox mode or specify a fixed region during initialization.

    Options:

    • apiKey: Your CloudConvert API key.
    • sandbox (optional): A boolean passed as the second argument. Set to true to use the Sandbox environment to avoid consuming quota.
    • region (optional): A string passed as the third argument to set a fixed region (e.g., 'us-east').
    import CloudConvert from 'cloudconvert';
    
    // Standard initialization
    const cloudConvert = new CloudConvert('api_key');
    
    // Initialization with Sandbox enabled
    const cloudConvertSandbox = new CloudConvert('api_key', true);
    
    // Initialization with a specific region
    const cloudConvertRegion = new CloudConvert('api_key', false, 'us-east');
  7. Create conversion jobs

    master

    Use cloudConvert.jobs.create() to define a job consisting of multiple tasks. Tasks can include importing files (via URL or upload), performing conversions, and exporting files (via URL).

    You can use the CloudConvert Job Builder to find available options for specific task types.

    import CloudConvert from 'cloudconvert';
    
    const cloudConvert = new CloudConvert('api_key');
    
    let job = await cloudConvert.jobs.create({
        tasks: {
            'import-my-file': {
                operation: 'import/url',
                url: 'https://my-url'
            },
            'convert-my-file': {
                operation: 'convert',
                input: 'import-my-file',
                output_format: 'pdf',
                some_other_option: 'value'
            },
            'export-my-file': {
                operation: 'export/url',
                input: 'convert-my-file'
            }
        }
    });
  8. Configure Job creation with JobTemplate

    master

    When creating a job via jobs.create(), you must provide a JobTemplate. This template defines the sequence of tasks to be executed.

    JobTemplate Structure

    • tasks: A TaskContainer object where each key is a unique name for a task, and the value is a task definition (including operation and its specific params).
    • tag (optional): A string to categorize jobs for easier filtering later.
    • webhook_url (optional): A URL to which CloudConvert will send webhook notifications about job updates.

    Task Definitions

    Each task in the tasks object must include an operation (e.g., 'import/url', 'convert', 'export/url') and the corresponding params required by that operation. You can also include ignore_error?: boolean to prevent a task failure from stopping the entire job.

    export interface JobTemplate {
        tasks: {
            [name: string]: any; // Each task must have a valid operation and params
        };
        tag?: string;
        webhook_url?: string;
    }
  9. Access API resources via the CloudConvert client

    master

    The CloudConvert instance provides access to several specialized resource objects for managing different parts of the API:

    • client.tasks: Manage individual tasks.
    • client.jobs: Manage conversion jobs.
    • client.users: Manage user information.
    • client.webhooks: Manage webhooks.
    • client.signedUrls: Manage signed URLs.
  10. Subscribe to real-time events via WebSockets

    master

    The CloudConvert client supports real-time updates using WebSockets. You can subscribe to specific channels and listen for events.

    Steps:

    1. Call subscribe(channel, event, callback).
    2. The client will automatically establish a connection to the appropriate Socket.io server (sandbox or production).
    3. When the event occurs on the specified channel, the callback is executed.
    4. Use closeSocket() to terminate the connection.

    Note: The channel is typically a job ID or a specific resource identifier.

    // Example: Subscribing to job events
    cloudconvert.subscribe('job_id_here', 'task.finished', (eventData) => {
      console.log('Task finished:', eventData);
    });
    
    // Later, close the connection
    cloudconvert.closeSocket();
  11. Subscribe to Job events

    master

    Use subscribeJobEvent to listen for specific real-time events related to a job via WebSockets. You must provide the job id, the specific JobEvent you want to listen for, and a callback function that receives the JobEventData.

    await cloudconvert.users.subscribeJobEvent(
      'job_id_here',
      'finished',
      (eventData) => {
        console.log('Job finished:', eventData);
      }
    );