View all our code samples

Using Needle in Node

Needle is a lightweight and flexible HTTP client for Node.js. It offers a simple and intuitive API for making HTTP requests and handling responses. Needle supports features like automatic decompression, streaming requests and responses, and multipart/form-data uploads.

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 needle = require('needle');
const fs = require('fs');

function convert(apiKey, params, endpoint='pdf') {
    if (!['pdf', 'png', 'jpg', 'webp'].includes(endpoint)) {
         throw new Error('Invalid endpoint');
    } 
    
    let options = {
        username: 'api',
        password: apiKey,
        json: params,
    }

    return new Promise((resolve, reject) => {
        needle.post(`https://api.pdfshift.io/v3/convert/${endpoint}`, params, options, function(err, resp) {
            if (err) reject(err);
            if ('filename' in params || 'webhook' in params) {
                // Return in JSON in this case
                resolve(JSON.parse(resp.body));
            }
            resolve(resp.body);
        });
    });
}

Here's how you can use the above code:

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

// Write the response body to a local file
fs.writeFile('result.pdf', body, 'binary')

We've tested this code with the latest version of Needle 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.