PubNub LogoDocs
SupportContact SalesLoginTry Our APIs

›API Reference

nodeJS

  • Getting Started
  • API Reference

    • Configuration
    • Publish & Subscribe
    • Presence
    • Access Manager
    • Channel Groups
    • Message Persistence
    • Mobile Push
    • Objects
    • Files
    • Message Actions
    • Miscellaneous
  • Status Events
  • Troubleshooting
  • Change Log
  • Feature Support
  • Platform Support

Utility Methods API for PubNub Node.js SDK

Close PubNub

Description

End all open requests and close the PubNub instance.

Basic Usage

Close pubnub.

pubnub.stop();

Decrypt

Description

This function allows to decrypt the data.

Method(s)

To decrypt the data you can use the following method(s) in Node.js V4 SDK.

  1. decrypt(data: string, customCipherKey: ?string)
    
    ParameterTypeRequiredDescription
    dataStringYesThe data to decrypt.
    customCipherKeyStringOptionalIf it's not provided, the cipher key from config will be used.

Basic Usage

Decrypt part of message

var decrypted = pubnub.decrypt(encrypted, 'myCipherKey'); // Pass the encrypted data as the first parameter in decrypt Method

Returns

It returns the decrypted data as an object.

Decrypt File

Description

This function allow to decrypt the file content/data.

Method(s)

To decrypt the file you can use the following method(s) in Node.js V4 SDK.

  1. pubnub.decryptFile(  key: string, file: PubNubFile): Promise<PubNubFile>;
    
    ParameterTypeRequiredDescription
    keyStringYesCipher key used for decryption.
    filePubNubFileYesFile to decrypt.

Basic Usage

// Node.js example
import fs from 'fs';

const fileBuffer = fs.readFileSync('./cat_picture_encrypted.jpg');

const file = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mimeType: 'image/jpeg' });

const decryptedFile = await pubnub.decryptFile('myCipherKey', file);

Returns

Returns a promise of PubNubFile

Encrypt

Description

This function allows to encrypt the data.

Method(s)

To encrypt the data you can use the following method(s) in Node.js V4 SDK.

  1. encrypt(data: string, customCipherKey: ?string)
    
    ParameterTypeRequiredDescription
    dataStringYesThe data to encrypt.
    customCipherKeyStringOptionalIf it's not provided, the cipher key from config will be used.

Basic Usage

Encrypt part of message

var sCypher = "testCypher";
var msgContent = "This is the data I wish to encrypt.";
console.log('msgContent: ' + msgContent);

// Encrypt with pubnub
var encryptedMessage = pubnub.encrypt(JSON.stringify(msgContent), sCypher);
console.log('encryptedMessage PN: ' + encryptedMessage);

Returns

It returns the encrypted data as string.

Encrypt File

Description

This function allow to encrypt the file content/data.

Method(s)

To encrypt the file you can use the following method(s) in Node.js V4 SDK.

  1. pubnub.encryptFile(  key: string, file: PubNubFile): Promise<PubNubFile>;
    
    ParameterTypeRequiredDescription
    keyStringYesCipher key used for encryption.
    filePubNubFileYesFile to encrypt.

Basic Usage

// Node.js example
import fs from 'fs';

const fileBuffer = fs.readFileSync('./cat_picture.jpg');

const file = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mimeType: 'image/jpeg' });

const encryptedFile = await pubnub.encryptFile('myCipherKey', file);

Returns

Returns a promise of PubNubFile

PubNub File

Description

Internal representation of the file used by the SDK. Depending on the environment, different methods can be used to extract the file.

Extracting the file

  • Methods supported in Node.js:
    • file.toBuffer() returns Promise<Buffer>
    • file.toStream() returns Promise<Readable>
    • file.toString(encoding: string) returns a string encoded using encoding (if not available, defaults to utf8)
  • Methods supported in a browser:
    • file.toFile() returns Promise<File>
    • file.toBlob() returns Promise<Blob>
    • file.toArrayBuffer() returns Promise<ArrayBuffer>
    • file.toString(encoding: string) returns returns a string encoded using encoding (if not available, defaults to utf8)
  • React and React Native:
    • file.toBlob() returns Promise<Blob>

Creating a file

pubnub.File.create(input: FileInput): PubNubFile;

FileInput represents a variety of possible inputs that represent a file in different environments.

Node.js

  • Using streams:

    {
        stream: Readable,
        name: string,
        mimeType?: string
    }
    
  • Using buffers:

    {
        data: Buffer,
        name: string,
        mimeType?: string
    }
    
  • Using strings:

    {
        data: string,
        encoding: string,
        name: string,
        mimeType?: string
    }
    

Browsers

  • Using File API

    File
    
  • Using strings:

    {
        data: string,
        name: string,
        mimeType?: string
    }
    
  • Using ArrayBuffer:

    {
        data: ArrayBuffer,
        name: string,
        mimeType?: string
    }
    

Reconnect

Description

Call the reconnect method to force the SDK to try and reach out PubNub.

Method(s)

To reconnect the data you can use the following method(s) in Node.js V4 SDK.

  1. reconnect()
    

    This method doesn't take any arguments.

Basic Usage

pubnub.reconnect();

setProxy

Description

Call setProxy() to instruct the SDK to assign or reassign a proxy configuration in run time.

Method(s)

To setProxy the data you can use the following method(s) in Node.js V4 SDK.

  1. setProxy({String hostname, Number port, String protocol})
    
    ParameterTypeRequiredDefaultsDescription
    hostnameStringYesSpecifies the IP address the or URI to use.
    portNumberYesSpecifies the port which the proxy will be listened.
    protocolStringOptionalhttpSupported Protocols are http, https, socks5, socks4 and pac.

Basic Usage

pubnub.setProxy({
    hostname: 'YOUR HOSTNAME HERE',
      port: 8080,
    protocol: 'YOUR PROTOCOL HERE'
});

Other Examples

  1. To delete the proxy in run time:

    pubnub.setProxy(null);
    

Time

Description

This function will return a 17 digit precision Unix epoch.

The timetoken is constructed using the following algorithm:
timetoken = (Unix epoch time in seconds) * 10000000

Example of creating a timetoken for a specific time and date

08/19/2013 @ 9:20pm in UTC = 1376961606
timetoken = 1376961606 * 10000000
timetoken = 13769616060000000

Method(s)

To fetch Time you can use the following method(s) in Node.js V4 SDK:

  1. time(Function callback)
    
    ParameterTypeRequiredDescription
    callbackFunctionYesCallback is called after a successful return.

Basic Usage

Get PubNub Timetoken

// assuming an initialized PubNub instance already exists
pubnub.time(function(status, response) {
    if (status.error) {
        // handle error if something went wrong based on the status object
    } else {
        console.log(response.timetoken);
    }
})

Response

//Example of status
{
    error: false,
    operation: 'PNTimeOperation',
    statusCode: 200
}

//Example of response
{
    timetoken: 15031768233407550
}

Other Examples

  1. Basic usage using Promises

    pubnub.time().then((timetoken) => {
        console.log(timetoken);
    }).catch((error) => {
        console.log(error)
    });
    

Push Notification Configuration

APNS2Configuration

Description

APNS2 configuration type.

Method(s)

  1. type APNS2Configuration = {  collapseId?: string,  expirationDate?: Date,  targets: Array<APNS2Target>}
    
    ParameterTypeRequiredDescription
    collapseIdStringOptionalNotification group / collapse identifier. Value will be used in APNS POST request as apns-collapse-id header value.
    expirationDateDateOptionalDate till which APNS will try to deliver notification to target device. Value will be used in APNS POST request as apns-expiration header value.
    targetsArray< APNS2Target >YesList of topics which should receive this notification.

APNSNotificationPayload

Description

APNSNotificationPayload instance provides access to options specific only to push notifications sent with APNs.

Properties

  1. ParameterTypeDescription
    configurationsArray< APNS2NotificationConfiguration *> *List of HTTP/2-based APNs delivery configurations.
    notificationHashHash with parameters which specify user-visible key-value pairs.
    payloadHashPlatform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device.
    silentBooleanWhether operation system should handle notification layout by default or not. alert, sound and badge will be removed from resulting payload if set to true.

APNS2Target

Description

APNS2 configuration target type.

Method(s)

  1. type APNS2Target = {  topic: string,  environment?: 'development' | 'production',  excludedDevices?: Array<string>}
    
    ParameterTypeRequiredDefaultsDescription
    topicStringYesNotifications topic name (usually it is bundle identifier of applicationfor Apple platform). Required only if pushGateway set to apns2.
    environmentStringOptionaldevelopmentEnvironment within which registered devices to which notifications should be delivered. Available:
    • development
    • production
    excludedDevicesArrayYesList of devices (their push tokens) to which this notification shouldn't be delivered.

FCMNotificationPayload

Description

FCMNotificationPayload instance provides access to options specific only to push notifications sent with FCM

Properties

  1. ParameterTypeDescription
    notificationHashHash with parameters which specify user-visible key-value pairs.
    dataHashCustom key-value object with additional information which will be passed to device along with displayable notification information. All object and scalar type value should be converted to strings before passing to this object. Keys shouldn't match: from, message_type or start with google or gcm. Also as key can't be used any word defined in this table
    silentBooleanWhether operation system should handle notification layout by default or not. notification key with it's content will be moved from root level under data key.
    iconStringIcon which should be shown on the left from notification title instead of application icon.
    tagStringUnique notification identifier which can be used to publish update notifications (they will previous notification with same tag).
    payloadHashPlatform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device.

MPNSNotificationPayload

Description

MPNSNotificationPayload instance provides access to options specific only to push notifications sent with MPNS

Properties

  1. ParameterTypeDescription
    backContentStringMessage which should be shown in notification body (text for back tile). 40 characters long to fit into tile.
    backTitleStringAdditional information which may explain reason why this notification has been delivered. Maximum 15 characters long.
    countNumberValue between 1-99 which will be shown on the tile.
    titleStringTitle of the tile.
    typeStringType of notification which should be presented to the user.
    payloadHashPlatform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device.

NotificationsPayload

Description

NotificationsPayload instance provides convenient method and properties which allow to setup notification for multiple platforms without getting into details how they should be formatted.
Builder instance contain additional set of properties which allow to fine tune payloads for particular platforms and even access to RAW payload dictionaries.

Method(s)

  1. ParameterTypeDescription
    subtitleStringAdditional information which may explain reason why this notification has been delivered.
    badgeNumberNumber which should be shown in space designated by platform (for example atop of application icon).
    soundStringPath to file with sound or name of system sound which should be played upon notification receive.
    debuggingBooleanWhether PubNub service should provide debug information about devices which received created notifications payload.
    apnsAPNSNotificationPayloadAccess to APNS specific notification builder.
    fcmFCMNotificationPayloadAccess to FCM specific notification builder.
  2. PubNub.notificationPayload(String title, String body)
    
    ParameterTypeRequiredDescription
    titleStringOptionalShort text which should be shown at the top of notification instead of application name.
    bodyStringOptionalMessage which should be shown in notification body (under title line).
  3. buildPayload(Array<String> platforms)
    
    ParameterTypeRequiredDescription
    platformsArrayYesList of platforms for which payload should be added to final dictionary. Available:
    • apns
    • apns2
    • fcm

Basic Usage

Create notification payload builder with pre-defined notification title and body:

  1. let builder = PubNub.notificationPayload('Chat invitation',
                                             'You have been invited to \'quiz\' chat');
    let messagePayload = builder.buildPayload(['apns2', 'fcm']);
    messagePayload.message = 'Max invited you to \'quiz\' chat room';
    messagePayload.roomID = 'ewuiogw9vewg0';
    
    pubnub.publish(
        {
            message: messagePayload,
            channel: 'chat-bot',
        },
        function (status, response) {
            // Handle publish results
        }
    );
    
  2. let builder = PubNub.notificationPayload('Chat invitation',
                                             'You have been invited to \'quiz\' chat');
    

Response

Hash with data, which can be sent with publish method call and trigger remote notifications for specified platforms.

Other Examples

  1. Generate simple notification payload for FCM and APNS:

    let builder = PubNub.notificationPayload('Chat invitation',
                                             'You have been invited to \'quiz\' chat');
    builder.sound = 'default';
    
    console.log(JSON.stringify(builder.buildPayload(['apns', 'fcm']), null, 2));
    

    Output

    {
        "pn_apns": {
            "aps": {
                "alert": {
                    "body": "You have been invited to 'quiz' chat",
                    "title": "Chat invitation"
                },
                "sound": "default"
            }
        },
        "pn_gcm": {
            "notification": {
                "body": "You have been invited to 'quiz' chat",
                "sound": "default",
                "title": "Chat invitation"
            }
        }
    }
    
  2. Generate simple notification payload for FCM and HTTP/2-based APNs (default configuration):

    let builder = PubNub.notificationPayload('Chat invitation',
                                             'You have been invited to \'quiz\' chat');
    builder.apns.configurations = [{ targets: [{ topic: 'com.meetings.chat.app' }] }];
    builder.sound = 'default';
    
    console.log(JSON.stringify(builder.buildPayload(['apns2', 'fcm']), null, 2));
    

    Output

    {
        "pn_apns": {
            "aps": {
                "alert": {
                    "body": "You have been invited to 'quiz' chat",
                    "title": "Chat invitation"
                },
                "sound": "default"
            },
            "pn_push": [
                {
                    "targets": [
                        {
                            "environment": "development",
                            "topic": "com.meetings.chat.app"
                        }
                    ],
                    "version": "v2"
                }
            ]
        },
        "pn_gcm": {
            "notification": {
                "body": "You have been invited to 'quiz' chat",
                "sound": "default",
                "title": "Chat invitation"
            }
        }
    }
    
  3. Generate simple notification payload for FCM and HTTP/2-based APNs (custom configuration):

    let configuration = [
        {
            collapseId: 'invitations',
            expirationDate: new Date(Date.now() + 10000),
            targets: [{ topic: 'com.meetings.chat.app' }]
        }
    ];
    let builder = PubNub.notificationPayload('Chat invitation',
                                             'You have been invited to \'quiz\' chat');
    builder.apns.configurations = [configuration];
    
    console.log(JSON.stringify(builder.buildPayload(['apns2', 'fcm']), null, 2));
    

    Output

    {
        "pn_apns": {
            "aps": {
                "alert": {
                    "body": "Chat invitation",
                    "title": "You have been invited to 'quiz' chat"
                }
            },
            "pn_push": [
                {
                    "collapse_id": "invitations",
                    "expiration": "2019-11-28T22:06:09.163Z",
                    "targets": [
                        {
                            "environment": "development",
                            "topic": "com.meetings.chat.app"
                        }
                    ],
                    "version": "v2"
                }
            ]
        },
        "pn_gcm": {
            "notification": {
                "body": "You have been invited to 'quiz' chat",
                "title": "Chat invitation"
            }
        }
    }
    

Example above show how to create notification payload which APNS will try to redeliver few times (if devices not active) and give up after 10 seconds since moment when it has been scheduled.

Additionally this invitation notification will be grouped along with other invitation notifications (using provided collapse_id as group identifier) and shown as one in notification center.

Returns

Configured and ready to use NotificationsPayload instance.

← Message ActionsStatus Events →
  • Close PubNub
    • Description
    • Basic Usage
  • Decrypt
    • Description
    • Method(s)
    • Basic Usage
    • Returns
  • Decrypt File
    • Description
    • Method(s)
    • Basic Usage
    • Returns
  • Encrypt
    • Description
    • Method(s)
    • Basic Usage
    • Returns
  • Encrypt File
    • Description
    • Method(s)
    • Basic Usage
    • Returns
  • PubNub File
    • Description
    • Extracting the file
    • Creating a file
  • Reconnect
    • Description
    • Method(s)
    • Basic Usage
  • setProxy
    • Description
    • Method(s)
    • Basic Usage
    • Other Examples
  • Time
    • Description
    • Method(s)
    • Basic Usage
    • Response
    • Other Examples
  • Push Notification Configuration
    • APNS2Configuration
    • APNSNotificationPayload
    • APNS2Target
    • FCMNotificationPayload
    • MPNSNotificationPayload
    • NotificationsPayload
© PubNub Inc. - Privacy Policy