View all our code samples

Using Got in Node

Got is a lightweight and flexible HTTP client for Node.js. It provides a simple API for making HTTP requests with support for Promises and async/await syntax. Got focuses on performance, ease of use, and extensibility.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Node:

const got = require('got');

async function convert(apiKey, params, endpoint='pdf') {

    if (!['pdf', 'png', 'jpg', 'webp'].includes(endpoint)){
        throw new Error('Invalid endpoint');
    }

    const response = await got.post(`https://api.pdfshift.io/v3/convert/${endpoint}`, {
        auth: 'api:' + apiKey,
        json: params,
        responseType: 'json'
    });

    if ('filename' in params || 'webhook' in params){
        return response.body;
    }

    return response.rawBody;
}

Here's how you can use the above code:

(async () => {
    const binary = await convert('sk_XXXXXXXXXXXXXX', { source: 'https://en.wikipedia.org/wiki/REST' });

    require('fs').writeFileSync('result.pdf', binary);
})()

We've tested this code with the latest version of Got and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.