Utility Methods API for PubNub JavaScript SDK

The methods on this page are utility methods that don't fit into other categories.

Encrypt

This function allows to encrypt the data.

Deprecated parameter

The cipherKey parameter in this method is deprecated. We recommend that you configure a seprate instance of the crypto module and use it for partial encryption.

If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.

Method(s)

To encrypt the data, you can use the following method(s) in JavaScript SDK.

encrypt(
data: string,
customCipherKey?: string
)
ParameterTypeRequiredDescription
datastring or bytesYesThe data to encrypt.
customCipherKeystringOptionalIf provided, the legacy encryption with 128-bit cipher key entropy is used.

Basic Usage

Encrypt part of message

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

// create a crypto module instance
const cryptoModule = PubNub.CryptoModule.aesCbcCryptoModule({
cipherKey: "pubnubenigma"
});

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

Returns

It returns the encrypted data as string.

Encrypt File

This function allow to encrypt the file content/data.

Deprecated

The key parameter in this method is deprecated. We recommend that you configure a seprate instance of the crypto module and use it for partial encryption.

If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.

Method(s)

To encrypt the file, you can use the following method(s) in JavaScript SDK.

pubnub.encryptFile(
key: string,
file: PubNubFile
): Promise<PubNubFile>;
ParameterTypeRequiredDescription
keystringOptionalCipher 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

Decrypt

This function allows to decrypt the data.

Deprecated parameter

The cipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.

If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.

Method(s)

To decrypt the data, you can use the following method(s) in JavaScript SDK.

decrypt(
data: string,
customCipherKey?: string
ParameterTypeRequiredDescription
datastringYesThe data to decrypt.
customCipherKeystringOptionalIf provided, the legacy encryption with 128-bit cipher key entropy is used. If not provided, the cryptoModule from PubNub config will be used.

For more information, refer to Crypto module configuration.

Basic Usage

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

Returns

It returns the decrypted data as an object.

Error Responses

If the decrypt() method fails, a verbose error with a reason for failure is thrown.

Decrypt File

This function allow to decrypt the file content/data.

Deprecated

This method uses the legacy encryption with 128-bit cipher key entropy. For more information, refer to Crypto module configuration.

Method(s)

To decrypt the file, you can use the following method(s) in JavaScript SDK.

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.

PubNubFile

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 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
    }

Disconnect

Call the disconnect method to force the SDK to stop all requests to PubNub server when there are active subscribe channels.

Method(s)

To disconnect the data transmission you can use the following method(s) in JavaScript SDK.

disconnect()

This method doesn't take any arguments.

Basic Usage

pubnub.disconnect()

Reconnect

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 JavaScript SDK.

reconnect()

This method doesn't take any arguments.

Basic Usage

pubnub.reconnect();

Time

This function will return a 17 digit precision Unix epoch.

Algorithm constructing the timetoken
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 JavaScript SDK

const timetoken = await pubnub.time();

Basic Usage

Get PubNub Timetoken

// assuming an initialized PubNub instance already exists
try {
const timetoken = await pubnub.time();
} catch (status) {
console.log("Something went wrong:", status);
}

Response

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

//Example of response
{
timetoken: 15031768233407550
}

Other Examples

Basic usage with Promises

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

setProxy

Call setProxy() to instruct the SDK to assign or reassign a proxy configuration in run time. This method is only available for NodeJS.

Method(s)

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

setProxy({String hostname, Number port, String protocol})
ParameterTypeRequiredDefaultDescription
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

Delete the proxy in run time

pubnub.setProxy(null);
Last updated on