Skip to content

abhinavr4/imagekit-nodejs

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ImageKit.io

ImageKit.io Node.js SDK

Node CI npm version codecov Try imagekit on RunKit License: MIT Twitter Follow

ImageKit Node.js SDK allows you to use image resizing, optimization, file uploading and other ImageKit APIs from applications written in server-side JavaScript.

Table of contents

Installation

Use the following command to download this module. Use the optional --save parameter if you wish to save the dependency in your package.json file.

npm install imagekit --save
# or
yarn add imagekit

Initialization

var ImageKit = require("imagekit");

var imagekit = new ImageKit({
    publicKey : "your_public_api_key",
    privateKey : "your_private_api_key",
    urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/"
});

Demo application

The fastest way to get started is by running the demo application in sample folder. Refer to the README file in sample folder.

Usage

You can use this NodeJS SDK for three different kinds of functions - URL generation, file uploads, and file management. The usage of the SDK has been explained below.

URL Generation

1. Using image path and image hostname or endpoint

This method allows you to create a URL using the path where the image exists and the URL endpoint (urlEndpoint) you want to use to access the image. You can refer to the documentation here to read more about URL endpoints in ImageKit and the section about image origins to understand about paths with different kinds of origins.

var imageURL = imagekit.url({
    path : "/default-image.jpg",
    urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    transformation : [{
        "height" : "300",
        "width" : "400"
    }]
});

This results in a URL like

https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400/default-image.jpg

2. Using full image URL

This method allows you to add transformation parameters to an existing, complete URL that is already mapped to ImageKit using the src parameter. Use this method if you have the absolute image URL stored in your database.

var imageURL = imagekit.url({
    src : "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg",
    transformation : [{
        "height" : "300",
        "width" : "400"
    }]
});

This results in a URL like

https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400

The .url() method accepts the following parameters

Option Description
urlEndpoint Optional. The base URL to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/
path Conditional. This is the path at which the image exists. For example, /path/to/image.jpg. Either the path or src parameter needs to be specified for URL generation.
src Conditional. This is the complete URL of an image already mapped to ImageKit. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg. Either the path or src parameter needs to be specified for URL generation.
transformation Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a chained transformation can be specified as different objects of the array. The complete list of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL.
transformationPosition Optional. The default value is path that places the transformation string as a path parameter in the URL. It can also be specified as query, which adds the transformation string as the URL's query parameter tr. If you use the src parameter to create the URL, then the transformation string is always added as a query parameter.
queryParameters Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and not necessarily related to ImageKit. Especially useful if you want to add some versioning parameter to your URLs.
signed Optional. Boolean. Default is false. If set to true, the SDK generates a signed image URL adding the image signature to the image URL. If you create a URL using the src parameter instead of path, then do correct urlEndpoint for this to work. Otherwise returned URL will have the wrong signature
expireSeconds Optional. Integer. Meant to be used along with the signed parameter to specify the time in seconds from now when the URL should expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly.

Examples of generating URLs

1. Chained Transformations as a query parameter

var imageURL = imagekit.url({
    path : "/default-image.jpg",
    urlEndpoint : "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    transformation : [{
        "height" : "300",
        "width" : "400"
    }, {
        "rotation" : 90
    }],
    transformationPosition : "query"
});
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400%3Art-90

2. Sharpening and contrast transforms and a progressive JPG image

There are some transforms like Sharpening that can be added to the URL with or without any other value. To use such transforms without specifying a value, specify the value as "-" in the transformation object. Otherwise, specify the value that you want to be added to this transformation.

var imageURL = imagekit.url({
    src : "https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg",
    transformation : [{
        "format" : "jpg",
        "progressive" : "true",
        "effectSharpen" : "-",
        "effectContrast" : "1"
    }]
});
//Note that because the `src` parameter was used, the transformation string gets added as a query parameter `tr`
https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=f-jpg%2Cpr-true%2Ce-sharpen%2Ce-contrast-1

3. Signed URL that expires in 300 seconds with the default URL endpoint and other query parameters

var imageURL = imagekit.url({
    path : "/default-image.jpg",
    queryParameters : {
        "v" : "123"
    },
    transformation : [{
        "height" : "300",
        "width" : "400"
    }],
    signed : true,
    expireSeconds : 300
});
https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400/default-image.jpg?v=123&ik-t=1567358667&ik-s=f2c7cdacbe7707b71a83d49cf1c6110e3d701054

List of supported transformations

See the complete list of transformations supported in ImageKit here. The SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is.

Supported Transformation Name Translates to parameter
height h
width w
aspectRatio ar
quality q
crop c
cropMode cm
x x
y y
focus fo
format f
radius r
background bg
border b
rotation rt
blur bl
named n
overlayX ox
overlayY oy
overlayFocus ofo
overlayHeight oh
overlayWidth ow
overlayImage oi
overlayImageTrim oit
overlayImageAspectRatio oiar
overlayImageBackground oibg
overlayImageBorder oib
overlayImageDPR oidpr
overlayImageQuality oiq
overlayImageCropping oic
overlayImageFocus oifo
overlayImageTrim oit
overlayText ot
overlayTextFontSize ots
overlayTextFontFamily otf
overlayTextColor otc
overlayTextTransparency oa
overlayAlpha oa
overlayTextTypography ott
overlayBackground obg
overlayTextEncoded ote
overlayTextWidth otw
overlayTextBackground otbg
overlayTextPadding otp
overlayTextInnerAlignment otia
overlayRadius or
progressive pr
lossless lo
trim t
metadata md
colorProfile cp
defaultImage di
dpr dpr
effectSharpen e-sharpen
effectUSM e-usm
effectContrast e-contrast
effectGray e-grayscale
original orig

File Upload

The SDK provides a simple interface using the .upload() method to upload files to the ImageKit Media Library. It accepts all the parameters supported by the ImageKit Upload API.

The upload() method requires at least the file and the fileName parameter to upload a file and returns a callback with the error and result as arguments. You can pass other parameters supported by the ImageKit upload API using the same parameter name as specified in the upload API documentation. For example, to specify tags for a file at the time of upload, use the tags parameter as specified in the documentation here.

Sample usage

// Using Callback Function

imagekit.upload({
    file : <url|base_64|binary>, //required
    fileName : "my_file_name.jpg",   //required
    extensions: [
        {
            name: "google-auto-tagging",
            maxTags: 5,
            minConfidence: 95
        }
    ]
}, function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises 

imagekit.upload({
    file : <url|base_64|binary>, //required
    fileName : "my_file_name.jpg",   //required
    extensions: [
        {
            name: "google-auto-tagging",
            maxTags: 5,
            minConfidence: 95
        }
    ]
}).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

If the upload succeeds, error will be null, and the result will be the same as what is received from ImageKit's servers. If the upload fails, error will be the same as what is received from ImageKit's servers, and the result will be null.

File Management

The SDK provides a simple interface for all the media APIs mentioned here to manage your files. You can use a callback function with all API interfaces. The first argument of the callback function is the error, and the second is the result of the API call. The error will be null if the API succeeds.

1. List & Search Files

Accepts an object specifying the parameters to be used to list and search files. All parameters specified in the documentation here can be passed as-is with the correct values to get the results.

// Using Callback Function

imagekit.listFiles({
    skip : 10,
    limit : 10
}, function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.listFiles({
    skip : 10,
    limit : 10
}).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

2. Get File Details

Accepts the file ID and fetches the details as per the API documentation here.

// Using Callback Function

imagekit.getFileDetails("file_id", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.getFileDetails("file_id")
}).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

3. Get File Metadata

Accepts the file ID and fetches the metadata as per the API documentation here.

// Using Callback Function
imagekit.getFileMetadata("file_id", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 
imagekit.getFileMetadata("file_id")
}).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

You can also pass the remote URL of the image to get metadata.

// Using Callback Function
imagekit.getFileMetadata("https://ik.imagekit.io/your_imagekit_id/sample.jpg", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 
imagekit.getFileMetadata("https://ik.imagekit.io/your_imagekit_id/sample.jpg")
}).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

4. Update File Details

Update parameters associated with the file as per the API documentation here. The first argument to the updateFileDetails method is the file ID, and a second argument is an object with the parameters to be updated.

// Using Callback Function

imagekit.updateFileDetails("file_id", { 
    tags : ['image_tag'],
    customCoordinates : "10,10,100,100",
    extensions: [
        {
            name: "google-auto-tagging",
            maxTags: 5,
            minConfidence: 95
        }
    ]
}, function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.updateFileDetails("file_id", {
    tags : ['image_tag'],
    customCoordinates : "10,10,100,100",
    extensions: [
        {
            name: "google-auto-tagging",
            maxTags: 5,
            minConfidence: 95
        }
    ]
}).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

5. Delete File

Delete a file as per the API documentation here. The method accepts the file ID of the file that has to be deleted.

// Using Callback Function

imagekit.deleteFile("file_id", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.deleteFile("file_id").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

6. Bulk Delete Files

Delete multiple files as per the API documentation here. The method accepts an array of file IDs of the files that have to be deleted.

// Using Callback Function

imagekit.bulkDeleteFiles(["fileIds"], function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.bulkDeleteFiles(["fileIds"]).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

7. Purge Cache

Programmatically issue a cache clear request as per the API documentation here. Accepts the full URL of the file for which the cache has to be cleared.

// Using Callback Function

imagekit.purgeCache("full_url", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.purgeCache("full_url").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

8. Purge Cache Status

Get the purge cache request status using the request ID returned when a purge cache request gets submitted as per the API documentation here

// Using Callback Function

imagekit.getPurgeCacheStatus("cache_request_id", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});


// Using Promises 

imagekit.getPurgeCacheStatus("cache_request_id").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

9. Bulk Add tags

Add tags to multiple files in a single request as per API documentation here. The method accepts an array of fileIDs of the files and an array of tags that have to be added to those files.

// Using Callback Function

imagekit.bulkAddTags(["fileIds"], ["tags"], function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.bulkAddTags(["fileIds"], ["tags"]).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

10. Bulk Remove tags

Remove tags from multiple files in a single request as per API documentation here. The method accepts an array of fileIDs of the files and an array of tags that have to be removed from those files.

// Using Callback Function

imagekit.bulkRemoveTags(["fileIds"], ["tags"], function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.bulkRemoveTags(["fileIds"], ["tags"]).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

11. Copy File

This will copy a file from one location to another as per API documentation here. This method accepts the source file's path and destination folder path.

// Using Callback Function

imagekit.copyFile("sourceFilePath", "destinationPath", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.copyFile("sourceFilePath", "destinationPath").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

12. Move File

This will move a file from one location to another as per API documentation here. This method accepts the source file's path and destination folder path.

// Using Callback Function

imagekit.moveFile("sourceFilePath", "destinationPath", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.moveFile("sourceFilePath", "destinationPath").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

13. Copy Folder

This will copy one folder into another as per API documentation here. This method accepts the source folder's path and destination folder path.

// Using Callback Function

imagekit.copyFolder("sourceFolderPath", "destinationPath", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.copyFolder("sourceFolderPath", "destinationPath").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

14. Move Folder

This will move one folder into another as per API documentation here. This method accepts the source folder's path and destination folder path.

// Using Callback Function

imagekit.moveFolder("sourceFolderPath", "destinationPath", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.moveFolder("sourceFolderPath", "destinationPath").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

15. Get bulk job status

This allows us to get a bulk operation status e.g. copy or move folder as per API documentation here. This method accepts jobId that is returned by copy and move folder operations.

// Using Callback Function

imagekit.getBulkJobStatus("jobId", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.getBulkJobStatus("jobId").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

16. Create Folder

This will create a new folder as per API documentation here. This method accepts folder name and parent folder path.

// Using Callback Function

imagekit.createFolder("folderName", "parentFolderPath", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.createFolder("folderName", "parentFolderPath").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

17. Delete Folder

This will delete the specified folder and all nested files & folders as per API documentation here. This method accepts the full path of the folder that is to be deleted.

// Using Callback Function

imagekit.deleteFolder("folderPath", function(error, result) {
    if(error) console.log(error);
    else console.log(result);
});

// Using Promises

imagekit.deleteFolder("folderPath").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
});

Utility functions

We have included the following commonly used utility functions in this package.

Authentication parameter generation

In case you are looking to implement client-side file upload, you are going to need a token, expiry timestamp, and a valid signature for that upload. The SDK provides a simple method that you can use in your code to generate these authentication parameters for you.

Note: The Private API Key should never be exposed in any client-side code. You must always generate these authentication parameters on the server-side

var authenticationParameters = imagekit.getAuthenticationParameters(token, expire);

Returns

{
    token : "unique_token",
    expire : "valid_expiry_timestamp",
    signature : "generated_signature"
}

Both the token and expire parameters are optional. If not specified, the SDK uses the uuid package to generate a random token and generate a valid expiry timestamp internally. token and expire are always returned in the response, no matter if they are provided as an input to this method or not.

Distance calculation between two pHash values

Perceptual hashing allows you to construct a hash value that uniquely identifies an input image based on an image's contents. ImageKit.io metadata API returns the pHash value of an image in the response. You can use this value to find a duplicate (or similar) image by calculating the distance between the two images' pHash value.

This SDK exposes pHashDistance function to calculate the distance between two pHash values. It accepts two pHash hexadecimal strings and returns a numeric value indicative of the level of difference between the two images.

const calculateDistance = () => {
    // asynchronously fetch metadata of two uploaded image files
    // ...
    // Extract pHash strings from both: say 'firstHash' and 'secondHash'
    // ...
    // Calculate the distance between them:
    const distance = imagekit.pHashDistance(firstHash, secondHash);
    return distance;
}

Distance calculation examples

imagekit.pHashDistance('f06830ca9f1e3e90', 'f06830ca9f1e3e90');
// output: 0 (same image)

imagekit.pHashDistance('2d5ad3936d2e015b', '2d6ed293db36a4fb');
// output: 17 (similar images)

imagekit.pHashDistance('a4a65595ac94518b', '7838873e791f8400');
// output: 37 (dissimilar images)

Rate limits

Except for upload API, all ImageKit APIs are rate limited to protect the infrastructure from excessive request rates and to keep ImageKit.io fast and stable for everyone.

When you exceed the rate limits for an endpoint, you will receive a 429 status code. The Node.js library reads the rate limiting response headers provided in API response and adds these in the error argument of callback or .catch when using promises. Please sleep/pause for the number of milliseconds specified by the value of X-RateLimit-Reset property before making additional requests to that endpoint.

Property Description
X-RateLimit-Limit The maximum number of requests that can be made to this endpoint in interval specified by X-RateLimit-Interval response header.
X-RateLimit-Reset The amount of time in milliseconds, before you can make another request to this endpoint. Pause/sleep your workflow for this duration.
X-RateLimit-Interval The duration of interval in milliseconds for which this rate limit was exceeded.

Support

For any feedback or to report any issues or general implementation support, please reach out to [email protected]

Links

License

Released under the MIT license.

About

Node.js SDK for ImageKit.io API.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 50.3%
  • JavaScript 49.7%