### Install dependencies Source: https://github.com/freeconvert/freeconvert-api-examples/blob/master/nodejs/README.md Run this command to install the required project dependencies. ```bash npm i ``` -------------------------------- ### Run API example script Source: https://github.com/freeconvert/freeconvert-api-examples/blob/master/python/README.md Execute the primary Python script to demonstrate task and job management. ```bash python3 01-tasks-and-jobs.py ``` -------------------------------- ### Install dependencies Source: https://github.com/freeconvert/freeconvert-api-examples/blob/master/python/README.md Install the required Python packages listed in the requirements file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Execute example script Source: https://github.com/freeconvert/freeconvert-api-examples/blob/master/nodejs/README.md Run the specific Node.js script to process tasks and jobs. ```bash node 01-tasks-and-jobs.js ``` -------------------------------- ### Execute Go API example Source: https://github.com/freeconvert/freeconvert-api-examples/blob/master/golang/README.md Run the specific Go script to initiate tasks and jobs via the FreeConvert API. ```bash go run 01-tasks-and-jobs.go ``` -------------------------------- ### Initialize Go dependencies Source: https://github.com/freeconvert/freeconvert-api-examples/blob/master/golang/README.md Run this command to clean up and download the necessary modules for the project. ```bash go mod tidy ``` -------------------------------- ### Complex Multi-Step Job with WebSocket Notifications Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Demonstrates importing from multiple sources, converting, merging into a PDF, creating a thumbnail, and archiving into a zip file using a complex job. It also shows how to set up WebSocket listeners for job completion notifications. ```javascript const { io } = require("socket.io-client"); const socket = io("https://notification.freeconvert.com/", { transports: ["websocket"], path: "/socket.io", auth: { token: `Bearer ${apiKey}` }, }); // Complex job: Create PDF from multiple images + thumbnail, archive as zip const jobResponse = await freeconvert.post("/process/jobs", { tasks: { // Import webpage as screenshot fcWebpage: { operation: "import/webpage", url: "https://www.freeconvert.com", }, webpageScreenshot: { operation: "convert", input: "fcWebpage", output_format: "png", options: { viewport_width: 300, png_compression_level: "lossy", png_convert_quality: 80, }, }, // Import additional images diceImage: { operation: "import/url", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png", }, treeImage: { operation: "import/url", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Larix_decidua_Aletschwald.jpg/800px-Larix_decidua_Aletschwald.jpg", }, // Merge 3 images into a PDF mergedPdf: { operation: "merge", input: ["webpageScreenshot", "diceImage", "treeImage"], output_format: "pdf", options: { pdf_page_size: "1240.2x1753.95", pdf_orientation: "portrait", pdf_image_alignment: "Center", enlarge_images_to_fit: true, }, }, // Create thumbnail with custom background thumbnail: { operation: "convert", input: "diceImage", output_format: "jpg", options: { image_resize_percentage: 60, background: "#FF9900", jpg_convert_compression_level: 80, }, }, thumbnailExport: { operation: "export/url", input: "thumbnail", filename: "Thumbnail.jpg", }, // Archive PDF and thumbnail as zip finalExport: { operation: "export/url", input: ["thumbnailExport", "mergedPdf"], archive_multiple_files: true, filename: "FinalPackage.zip", }, }, }); const jobId = jobResponse.data.id; console.log("Created job:", jobId); // Setup WebSocket listeners and subscriptions socket.on("job_completed", async (data) => { const jobGetResponse = await freeconvert.get(`/process/jobs/${data.id}`); const job = jobGetResponse.data; const exportTask = job.tasks.find((t) => t.name === "finalExport"); console.log("Download URL:", exportTask.result.url); socket.disconnect(); }); socket.emit("subscribe", `job.${jobId}`); ``` -------------------------------- ### Convert Files with Options Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Performs file format conversion with advanced settings like resizing, background color, and compression. ```javascript // Single conversion task referencing an import task const convertTaskResponse = await freeconvert.post("/process/convert", { input: "existing_task_id", output_format: "jpg", options: { background: "#FFFFFF", image_custom_width: 100, image_custom_height: 100, }, }); // Image conversion with resize and background options const imageConvertOptions = { operation: "convert", input: "sourceTaskName", output_format: "jpg", options: { image_resize_percentage: 60, background: "#FF9900", jpg_convert_compression_level: 80, }, }; ``` -------------------------------- ### Import Webpage as Screenshot Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Captures a webpage as an image and converts it to a specific format using a job-based workflow. ```javascript // Import a webpage for screenshot capture const webpageResponse = await freeconvert.post("/process/import/webpage", { url: "https://www.freeconvert.com", }); // Convert the webpage to PNG with custom viewport const jobResponse = await freeconvert.post("/process/jobs", { tasks: { fcWebpage: { operation: "import/webpage", url: "https://www.freeconvert.com", }, webpageScreenshot: { operation: "convert", input: "fcWebpage", output_format: "png", options: { viewport_width: 300, png_compression_level: "lossy", png_convert_quality: 80, }, }, }, }); ``` -------------------------------- ### Configure FreeConvert API Client Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Initializes an Axios instance with the required base URL and Bearer token authentication header. ```javascript const axios = require("axios"); const apiKey = "your_api_key_here"; const freeconvert = axios.create({ baseURL: "https://api.freeconvert.com/v1", headers: { "Content-Type": "application/json", "Accept": "application/json", "Authorization": `Bearer ${apiKey}`, }, }); ``` -------------------------------- ### Implement Real-time WebSocket Updates Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Connect to the FreeConvert notification service to receive task and job status events. Requires an active API key for authentication. ```javascript const { io } = require("socket.io-client"); // Initialize WebSocket connection const socket = io("https://notification.freeconvert.com/", { transports: ["websocket"], path: "/socket.io", auth: { token: `Bearer ${apiKey}` }, }); // Create a job const jobResponse = await freeconvert.post("/process/jobs", { tasks: { myImport1: { operation: "import/url", url: "https://cdn.freeconvert.com/logo_theme.svg", filename: "logo.svg", }, myConvert1: { operation: "convert", input: "myImport1", output_format: "jpg", }, myExport1: { operation: "export/url", input: "myConvert1", filename: "my-converted-file.jpg", }, }, }); const jobId = jobResponse.data.id; // Listen for events socket.on("task_started", (data) => { console.log("Task started:", data.name); }); socket.on("task_completed", (data) => { console.log("Task completed:", data.name); socket.emit("unsubscribe", `task.${data.id}`); }); socket.on("task_failed", (data) => { console.log("Task failed:", data.name); socket.emit("unsubscribe", `task.${data.id}`); }); socket.on("job_completed", (data) => { console.log("Job completed:", data.id); socket.emit("unsubscribe", `job.${data.id}`); socket.disconnect(); }); socket.on("job_failed", (data) => { console.log("Job failed:", data.id); socket.emit("unsubscribe", `job.${data.id}`); socket.disconnect(); }); // Subscribe to job and all task events socket.emit("subscribe", `job.${jobId}`); jobResponse.data.tasks.forEach((task) => { socket.emit("subscribe", `task.${task.id}`); }); ``` -------------------------------- ### Import File from URL Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Creates a task to import a file from a publicly accessible URL for subsequent processing. ```javascript // Create an import task from a URL const taskResponse = await freeconvert.post("/process/import/url", { url: "https://cdn.freeconvert.com/logo_theme.svg", filename: "logo.svg", }); const taskId = taskResponse.data.id; console.log("Created task:", taskId); // The task ID can be used as input for subsequent conversion tasks ``` -------------------------------- ### Upload File Directly Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Uploads a local file using a pre-signed URL obtained from an import task, then processes it in a conversion job. ```javascript const FormData = require("form-data"); const fs = require("fs"); // Step 1: Create an upload task to get the upload URL const uploadTaskResponse = await freeconvert.post("/process/import/upload"); const uploadTaskId = uploadTaskResponse.data.id; const uploaderForm = uploadTaskResponse.data.result.form; // Step 2: Prepare form data with required parameters const formData = new FormData(); for (const parameter in uploaderForm.parameters) { formData.append(parameter, uploaderForm.parameters[parameter]); } formData.append("file", fs.createReadStream("myvideo.mp4")); // Step 3: Submit the upload await axios.post(uploaderForm.url, formData, { headers: { "Content-Type": "multipart/form-data" }, }); // Step 4: Use the uploaded file in a conversion job const jobResponse = await freeconvert.post("/process/jobs", { tasks: { myConvert1: { operation: "convert", input: uploadTaskId, output_format: "mp3", }, myExport1: { operation: "export/url", input: "myConvert1", filename: "my-converted-file.mp3", }, }, }); ``` -------------------------------- ### Create Jobs with Chained Tasks Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Defines a workflow where tasks reference each other by name to create a processing pipeline. ```javascript const jobResponse = await freeconvert.post("/process/jobs", { tasks: { myImport1: { operation: "import/url", url: "https://cdn.freeconvert.com/logo_theme.svg", filename: "logo.svg", }, myConvert1: { operation: "convert", input: "myImport1", // Reference the import task by name output_format: "jpg", options: { background: "#FFFFFF", image_custom_width: 100, image_custom_height: 100, }, }, myExport1: { operation: "export/url", input: "myConvert1", // Reference the convert task by name filename: "my-converted-file.jpg", }, }, }); const jobId = jobResponse.data.id; console.log("Created job:", jobId); ``` -------------------------------- ### Merge Multiple Files into PDF Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Combines multiple input files into a single output document using the merge operation. ```javascript const jobResponse = await freeconvert.post("/process/jobs", { tasks: { image1: { operation: "import/url", url: "https://example.com/page1.png", }, image2: { operation: "import/url", url: "https://example.com/page2.png", }, image3: { operation: "import/url", url: "https://example.com/page3.jpg", }, mergedPdf: { operation: "merge", input: ["image1", "image2", "image3"], output_format: "pdf", options: { pdf_page_size: "1240.2x1753.95", pdf_orientation: "portrait", pdf_image_alignment: "Center", enlarge_images_to_fit: true, }, }, myExport: { operation: "export/url", input: "mergedPdf", filename: "merged-document.pdf", }, }, }); ``` -------------------------------- ### Export Results and Archives Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Generates downloadable URLs for processed files, with support for archiving multiple inputs into a single zip file. ```javascript // Single file export const singleExport = { operation: "export/url", input: "myConvert1", filename: "my-converted-file.jpg", }; // Archive multiple files as zip const archiveExport = { operation: "export/url", input: ["thumbnailExport", "mergedPdf"], archive_multiple_files: true, filename: "FinalPackage.zip", }; ``` -------------------------------- ### Handle Job Results and Errors Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Inspect job and task status objects to retrieve download URLs or error details. Assumes a polling mechanism is used to wait for job completion. ```javascript const jobResponse = await freeconvert.post("/process/jobs", { tasks: { myImport1: { operation: "import/url", url: "https://cdn.freeconvert.com/logo_theme.svg", filename: "logo.svg", }, myConvert1: { operation: "convert", input: "myImport1", input_format: "mp4", // Wrong format to demonstrate error handling output_format: "mp3", }, myExport1: { operation: "export/url", input: "myConvert1", }, }, }); // Wait for completion then inspect results const job = await waitForJobByPolling(jobResponse.data.id); if (job.status === "completed") { console.log("Job completed successfully."); } else { console.log(`Job failed. [${job.result.errorCode}] - ${job.result.msg.trim()}`); } // Check individual task results for (const task of job.tasks) { if (task.status === "completed") { console.log(`Task ${task.name} completed. URL: ${task.result.url}`); } else { console.log(`Task ${task.name} failed. [${task.result.errorCode}] - ${task.result.msg.trim()}`); } } ``` -------------------------------- ### Poll Task and Job Status Source: https://context7.com/freeconvert/freeconvert-api-examples/llms.txt Tracks the progress of tasks or jobs by polling their status endpoints until completion or failure. ```javascript async function waitForSeconds(seconds) { await new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } // Poll a single task async function pollTask(taskId) { for (let i = 0; i < 10; i++) { await waitForSeconds(2); const taskGetResponse = await freeconvert.get(`/process/tasks/${taskId}`); const task = taskGetResponse.data; console.log("Task status:", task.status); if (task.status === "completed" || task.status === "failed") { return task; } } throw new Error("Polling timed out"); } // Poll a job (completes when all child tasks complete) async function pollJob(jobId) { for (let i = 0; i < 10; i++) { await waitForSeconds(2); const jobGetResponse = await freeconvert.get(`/process/jobs/${jobId}`); const job = jobGetResponse.data; console.log("Job status:", job.status); if (job.status === "completed") { const exportTask = job.tasks.find((t) => t.name === "myExport1"); console.log("Download URL:", exportTask.result.url); return job; } else if (job.status === "failed") { return job; } } throw new Error("Polling timed out"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.