• Instructions to Ask a Question

    Click on the "Ask a Question" button and select the application for which you would like to ask questions.

    We have 5 different products namely - Pabbly Connect, Pabbly Subscription Billing, Pabbly Email Marketing, Pabbly Form Builder, Pabbly Email Verification.

    The turnaround time is 24 hrs (Business Hours - 10.00 AM to 6.00 PM IST, Except Saturday and Sunday). So your kind patience will be highly appreciated!

    🚀🚀Exclusive Discount Offer

    Just in case you're looking for any ongoing offers on Pabbly, you can check the one-time offers listed below. You just need to pay once and use the application forever -
     

    🔥 Pabbly Connect One Time Plan for $249 (🏆Lifetime Access) -  View offer 

    🔥 Pabbly Subscription Billing One Time Plan for $249 (🏆Lifetime Access) - View offer

JavaScript Code by Pabbly

Introduction

You can extend the functionality of your Pabbly Connect workflow by using the most widely used web programming language, JavaScript, with Code by Pabbly : JavaScript action.

Some of use cases include:
  • Date transformations or data type conversions.
  • Use custom regular expressions to extract data like emails or tracking numbers from large text blobs.
  • Make an extra API call to a different service with fetch without building a full dev app.
  • Process your data in a way that you think is better than other apps onboard.
  • Do your personalized processing or calculations which aren’t currently possible with other apps.
  • Perform multiple tasks in a single step.
Warning - This step involves programming, so be careful! To use this, you probably need to be a coder, though you are welcome to play about with it. There is no technical help for errors in your code!

Note: The environment is Node.js v18.x which runs AWS SDK for JavaScript v3. Your code can only run for a limited amount of time i.e. up to 25 seconds and within a limited amount of memory i.e. up to 128MB. If you exceed those limits - your script will be killed.



Section 1.
Variable and function declarations


Inside Code by Pabbly: JavaScript module, you can declare the variables as you do in JavaScript basic programming using `let`, `const`, `var` depending upon your need.
  • Entire content you write in or enter into the JavaScript Code field is internally wrapped in an async function, like this:
    JavaScript:
    async function name() {
        // Predefined constants to use 3 popular libraries. (Ref.: section 7):-
        const CryptoJS = …; const _ =  …;  const moment = …;
        // Pre-declared variable:-
        var output;
    
        // Your code:-
        ... ... ...
        ... ... ...
    
        return output;
    }
  • The wrapper function has some predefined constants, namely CryptoJS, _, and moment and a predefined variable, namely output.
  • You can use await keyword if required.

Here is a sample JavaScript code with which, you can get the idea of using variables and performing operations on them to return the desired output.

JavaScript:
//initializing variables
let data = {
 "first_name": "Pabbly", "last_name": "Connect", "invoice_id": 123456, "total_price": 55.50, "line_items": [ { "product_id": 123, "name": "world", "price": 5.50 }, { "product_id": 234, "name": "planet", "price": 11.00 } ] };

let lineItems = data.line_items;
let totalPrice = 0;

//Javascript loop
for (let i = 0; i < lineItems.length; i++) {
  totalPrice += lineItems[i].price;
};

//Output or returning result
return JSON.stringify({"totalPrice":totalPrice});

Check the below screenshot of executing the above code

1669452362870.png



Section 2.
Return a value: obtain the final output/result of the execution


The returned a value will be available under the label Output in the step Response.
You have two ways to return your required value - using a return statement, using the `output` variable instead of a return statement. Follow any one of them, as demonstrated below.

2.1. Using a return statement:
JavaScript:
// Convert a given paragraph to uppercase and then extract sentences from it:-

var para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.';

var modification1 = para.toUpperCase();
var modification2 = modification1.replaceAll('. ', '.*');
var sentences = modification2.split('*');

return sentences;
1694451933121.png

2.2. Using the `output` variable instead of a return statement:

Assign your required value to our pre-declared variable `output`. The last assigned value of output will be returned as your execution result.​
JavaScript:
// Convert a given paragraph to uppercase and then extract sentences from it:-

var para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.';

var modification1 = para.toUpperCase();
var modification2 = modification1.replaceAll('. ', '.*');
output = modification2.split('*');

1694453033416.png

Notice that the outcome (the step Response) is the same.



Section 3.
Logging: printing a variable for testing/debugging


Logging is optional. In order to check (print) intermediate values of the execution, you can use the following console methods: log(), error(), warn(), and debug().
All the printings by these methods will be visible under the label Logs in the step Response.

JavaScript:
// Convert a given paragraph to uppercase and then extract sentences from it:-

var para = 'Code by Pabbly is a freedom to process data in my own way. It allows me to perform multiple tasks in a single step. It supports JavaScript and Python.';

var modification1 = para.toUpperCase();
console.log(modification1);  // logging

var modification2 = modification1.replaceAll('. ', '.*');
var sentences = modification2.split('*');
console.log(JSON.stringify(sentences));  // logging

return sentences;  // the output (result)

1694454871395.png


Tip:
To print an array or object, stringify it first.
JavaScript:
console.log(JSON.stringify(sentences));

Important:
Logging option is not for obtaining the final output of the workflow step. To obtain the final output follow Section 2 above.



Section 4.
Example: Mathematical Expression - divide by five


JavaScript:
let num = 125;
return {
  result: Number(num)/5
};

1669444972967.png



Section 5.
Example: Using Regex to extract emails from given string


JavaScript:
let string = "Here are the emails [email protected], [email protected] and [email protected]";
return {
  Emails: (string.match(/([\w._-]+@[\w._-]+\.[\w._-]+)/gi) || [])[0]
};

1669445447541.png



Section 6.
Example: Use
fetch()

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

GET API Call Example
JavaScript:
//Defining headers
var myHeaders = new Headers();

//Initializing header with required values like, API Key, Content type etc.
myHeaders.append("X-API-Key", "HE48Q2LUVB6OXXXXXX5BARMGUSHS");
myHeaders.append("X-Account-Name", "MyAccount");

var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};

//Return statement with fetch function
return fetch("https://api.newzenler.com/api/v1/users?limit=1&search=john.doe@gmail",
requestOptions) .then(response => response.json()) .then(result => result.data) .catch(error => console.log('error', error));

1669379952763.png


POST API Call Example

JavaScript:
//Defining headers
var myHeaders = new Headers();

//Pass specific headers if required like, API Key, Token, Content Type etc..
myHeaders.append("x-api-key", "XLgggHyhde887887");
myHeaders.append("Content-Type", "application/json");

//API request body JSON payload
var raw = JSON.stringify({
"name": "John Doe",
"email": "[email protected]",
"phone": "877878898"
});

var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw, redirect: 'follow'
};

//Return statement with fetch function
return fetch("https://webhook.site/059ceed3-7545-4f8f-9852-e7023ce6f4a9", requestOptions) .then(response => response.text()) .then(result => result) .catch(error => console.log('error', error));

1669446127750.png



Section 7.
Available JavaScript libraries


The module has been reinforced with three popular JavaScript libraries, namely CryptoJS, Lodash, and Moment. These libraries are ready to access through our pre-defined identifiers CryptoJS, _, and moment respectively.

7.1 CryptoJS
CryptoJS is a growing collection of standard and secure cryptographic algorithms like, MDF, SHA1, SHA2, AES, HMAC, etc. implemented in JavaScript using best practices and patterns.

JavaScript:
//initialize varaibales
var public_api_key = "7e151e4060d6497111ed15565351b4332";
var secret_key = "8ad52a1d5d619835566a3848f3a6edg";

//Getting current timestamp
var timestamp = Math.floor(new Date().valueOf()/1000);

//Calculating hash HMAC using CryptoJs
var hash = CryptoJS.HmacSHA1(public_api_key + timestamp, secret_key);

//Returning the output
return {
"public_api_key":public_api_key, "timestamp":timestamp, "hash":hash.toString()
};
1669451133566.png
7.2. Moment.js
A JavaScript date library for parsing, validating, manipulating, and formatting dates.
JavaScript:
let now = moment().format('LLLL');
let locale = moment.locale();
let format = moment("10/08/2022").format("MM-DD-YYYY");
let day = moment("2022-10-08").format("dd");

output = {
"now":now,
"locale":locale,
"format":format,
"day":day
};

1669450822226.png
7.3 Lodash
Lodash is a JavaScript library that works on the top of underscore.js. It helps in working with arrays, strings, objects, numbers, etc. It provides us with various inbuilt functions and uses a functional programming approach which that coding in JavaScript easier to understand because instead of writing repetitive functions, tasks can be accomplished with a single line of code.

JavaScript:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];

// the `_.matches` iteratee shorthand.
return _.filter(users, { 'age': 36, 'active': true });
1669448308325.png

Troubleshooting​

Problem​
Possible Cause​
Solution​
In automation my Code step shows Error: SyntaxError: Invalid or unexpected token. If I copy the sent code from the Task History ('Data In' tab), and paste it into a Code input field, it runs fine.The data you pass to Code contains: HTML tags and/or line breaks within strings wrapped with "" or ''.Before using in Code, sanitize your data with the following actions.
  1. Text Formatter > Text (Basic Formatting) > Remove HTML Tags.
  2. Text Formatter > Replace Text
    Find: \r, Replace: {{space}}.
  3. Text Formatter > Replace Text
    Find: \n, Replace: {{space}}.
Note: line breaks in `` wrapped strings won't break the syntax.
Code:
let data = `This is a sample with \n newlines and more.`
return data;

Note: line breaks in `` wrapped strings won't break the syntax in JSON.
Code:
let text= `This is a sample with \n newlines and more.`;
const data = JSON.stringify([{"text": text}]);

return data;
My Code step shows Logs, but not the output.Missing a return or output statement in right place.You have two ways to obtain (return) your required value. If you want to obtain the value of x, write any one of the following statements:
  • return x;
  • output = x;
The returned a value will be available under the label Output in the step Response.
See demos in Section 2 of this guide.
My Code works sometimes, but sometimes doesn't.
  1. Double check logic in your code.
  2. In Task History, inspect the 'Data In' tab of the failed execution. Turn off Simple Format and check the value of "code" key. Check whether it has any syntax issue.
 

Attachments

  • 1669377435416.png
    1669377435416.png
    40.4 KB · Views: 134
  • 1669380295937.png
    1669380295937.png
    40.9 KB · Views: 145
  • 1669444600709.png
    1669444600709.png
    56.1 KB · Views: 1,018
  • 1669445971237.png
    1669445971237.png
    46.2 KB · Views: 130
Last edited by a moderator:
Top