Skip to main content

Execute code

This allows you to securely run code in a controlled environment, and return the results. This guide will explain how to structure your code to work seamlessly with this App.

Functions​

Execute JavaScript​

This function allows you to run JavaScript code in a controlled environment, making it possible to execute custom scripts, fetch and manipulate data, and return the results.

Input parameters​

ParameterUsageMandatory
JavaScript CodeType the code you want to run.Yes

Response parameters​

ParameterUsage
resultThe result defined in your function.
errorThis field will contain an error message if the code fails.

JavaScript Execution Environment​

When you execute JavaScript code in this tool, it runs in Node.js v20. This version of Node.js is built on the V8 JavaScript engine and supports the latest ECMAScript features, up to ECMAScript 2023 (ES14).

Key Features Supported in Node.js v20:​

  • Public and Private Class Fields: Define fields and private methods directly within class definitions.
  • Optional Chaining (?.): Safely access nested object properties without causing runtime errors.
  • Nullish Coalescing (??): Provide default values for null or undefined variables.
  • Logical Assignment Operators (&&=, ||=, ??=): Combine logical operators with assignment in a concise way.
  • BigInt: Support for arbitrary precision integers, useful for handling very large numbers.
  • Array findLast() and findLastIndex(): New array methods to search from the end of an array.

Available Modules​

The following commonly used modules are pre-installed and ready for use in your scripts:

  • URL: Provides utilities for parsing and manipulating URLs.
  • crypto: Offers cryptographic functionalities such as hashing, encryption, and signing.
  • buffer: Allows handling and manipulation of raw binary data.
  • util: Provides utility functions such as promisify and format.
  • dns: Allows DNS resolution and domain name lookups.
  • axios: A popular promise-based HTTP client for making requests to external APIs.
  • superagent: Another powerful HTTP client that supports promises and a wide range of features.
  • node-fetch: A lightweight module that implements the fetch API for making HTTP requests in Node.js.

Important Limitation​

danger

Only the modules explicitly listed above are supported. Any attempt to import packages that are not pre-installed will result in an error.

By leveraging the latest ECMAScript features and the pre-installed modules, you can write modern JavaScript code with confidence, knowing that it will run in a highly efficient and up-to-date environment.

Examples​

1. Basic Function Example: Arithmetic Operations​

The App allows you to define JavaScript functions and return results from them. Here’s an example of a simple function that performs basic arithmetic operations:

const math = () => {

let a, b;

a = [MACRO]special_random(|2|NUMBER)[#MACRO];
b = 2;

return {
"sum": a + b,
"subtract": a - b,
"multiply": a * b,
"divide": a / b
};
};

math();

Explanation:

  • Defining the Function: The math function is defined to perform four basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers.
  • Returning the Result: The function returns an object containing the results of these operations.
  • Execution: At the end of your code, the function is called (math();), which is necessary for the App to process the function and return the result.
tip

You can place @ variables and MACROs in the code, but remember that if the result of the @ variable, for example, is a string, to enclose it between quotes or the JavaScript may fail. The replacement of the @ variables and MACROs will be done BEFORE running the code, not while the code runs.

2. Basic Function Example: Getting URL information​

In this example, we will use the URL module to extract information from an URL. More information about the module at https://nodejs.org/api/url.html

const getURLInfo = () => {

const myUrl = new URL('https://example.com:8080/pathname?search=test#hash');

return {
"protocol": myUrl.protocol,
"host": myUrl.host,
"origin": myUrl.origin,
"pathname": myUrl.pathname,
"hostname": myUrl.hostname,
"port": myUrl.port,
"search": myUrl.search,
"hash": myUrl.hash
};
};

getURLInfo();

3. Basic Function Example: Create hash of a text​

In this example, we will use the Crypto module to hash a text. More information about the module at https://nodejs.org/api/crypto.html

const hashText = () => {

return {
"hash": crypto.createHash('sha256').update('my_text').digest('hex')
};
};

hashText();

4. Basic Function Example: Format a string​

In this example, we will use the util module to format a string. More information about the module at https://nodejs.org/api/util.html

const formatText = () => {

return {
"score": util.format('%s: %d', 'My score is', 100)
};
};

formatText();

5. Basic Function Example: Get DNS information​

In this example, we will use the dns module to get DNS information of a domain. More information about the module at https://nodejs.org/api/dns.html

const getDNSInfo = async () => {

const dns_result = await dns.lookup('example.com');

return {
"dns": util.format('address: %j family: IPv%s', dns_result.address, dns_result.family),
};
};

getDNSInfo();

6. Advanced Function Example: Fetching and Enriching Data​

In more complex scenarios, you might want to fetch data from an external API, process that data, and return an enriched result.

Here’s an example that demonstrates this that uses the axios library to do the request :

Axios library example

// Using Axios library
const fetchAndFormatUsers = async () => {

let users = [],
response,
macro_date
;

let url = "https://reqres.in/api/users?page=1";

response = await axios.get(url);
users = response.data.data;
macro_date = "[MACRO]date(Y-m-d H:i:s)[#MACRO]";

const promises = users.map(async user => {

let avatar_response,
avatar_base64,
content_type,
buffer_body
;

// Add full_name property
user.full_name = `${user.first_name} ${user.last_name}`;

// Fetch the avatar image and encode it to Base64
avatar_response = await axios.get(user.avatar, {
responseType: 'arraybuffer' // Ensures the data is returned as a binary buffer
});
content_type = avatar_response.headers['content-type'];
buffer_body = avatar_response.data;

avatar_base64 = Buffer.from(buffer_body).toString('base64');
user.avatar_base64 = `data:${content_type};base64,${avatar_base64}`;

// All the users will have the same current_date as the MACRO was replaced before executing the code
user.current_date = macro_date;

return user;
});

// Wait for all promises to resolve
return Promise.all(promises);
}

fetchAndFormatUsers();

You can use these three libraries: axios, superagent and node-fetch to make external requests and here they are two examples using them.

Superagent library example

// Using superagent library
const fetchAndFormatUsers = async () => {

let users = [],
response,
macro_date
;

let url = "https://reqres.in/api/users?page=1";

response = await superagent.get(url);
users = response.body.data;
macro_date = "[MACRO]date(Y-m-d H:i:s)[#MACRO]";

const promises = users.map(async user => {

let avatar_response,
avatar_base64,
content_type,
buffer_body
;

// Add full_name property
user.full_name = `${user.first_name} ${user.last_name}`;

// Fetch the avatar image and encode it to Base64
avatar_response = await superagent.get(user.avatar).responseType('blob'); // 'blob' for binary data
content_type = avatar_response.type;
buffer_body = avatar_response.body;

avatar_base64 = Buffer.from(buffer_body).toString('base64');
user.avatar_base64 = `data:${content_type};base64,${avatar_base64}`;

// All the users will have the same current_date as the MACRO was replaced before executing the code
user.current_date = macro_date;

return user;
});

// Wait for all promises to resolve
return Promise.all(promises);
}

fetchAndFormatUsers();

Node-fetch library example

// Using node-fetch library
const fetchAndFormatUsers = async () => {

let users = [],
response,
macro_date
;

let url = "https://reqres.in/api/users?page=1";

response = await fetch(url);
const data = await response.json(); // Convert the response to JSON
users = data.data;
macro_date = "[MACRO]date(Y-m-d H:i:s)[#MACRO]";

const promises = users.map(async user => {

let avatar_response,
avatar_base64,
content_type,
buffer_body
;

// Add full_name property
user.full_name = `${user.first_name} ${user.last_name}`;

// Fetch the avatar image and encode it to Base64
avatar_response = await fetch(user.avatar);
content_type = avatar_response.headers.get('content-type');
buffer_body = await avatar_response.arrayBuffer(); // Get an ArrayBuffer from the response

avatar_base64 = Buffer.from(buffer_body).toString('base64');
user.avatar_base64 = `data:${content_type};base64,${avatar_base64}`;

// All the users will have the same current_date as the MACRO was replaced before executing the code
user.current_date = macro_date;

return user;
});

// Wait for all promises to resolve
return Promise.all(promises);
}

fetchAndFormatUsers();

Explanation:

  • Async function: The fetchAndFormatUsers() function is an asynchronous function that uses async/await for handling asynchronous operations, such as API requests.
  • Fetching data: It fetches user data from a public API (https://reqres.in/api/users?page=1).
  • Processing each user: For each user, the function:
    • Combines the first_name and last_name properties into a full_name property.
    • Fetches the user’s avatar image, converts it to a Base64 string, and includes it in the output.
    • Adds a current_date property, where you can replace the [MACRO]date(Y-m-d H:i:s)[#MACRO] with a real timestamp or another dynamic value.
  • Handling promises: Since the avatar fetching is asynchronous, Promise.all(promises) ensures that the function waits for all avatar processing to complete before returning the result.