How to use Javascript in your automation

Combine the power of no-code and code to manipulate web pages and data to your liking. This guide will teach you how to use Axiom.ai’s Write JavaScript step to inject custom code into your automations. Find the "Write JavaScript" step in your Step Finder to get started.

For the best experience when using the “Write JavaScript" step, we recommend running your automations in the desktop application.

Check out our other useful JavaScript snippets for more inspiration.

# Creating scripts


The Write JavaScript step provides the ability to enter your JavaScript in a basic code editor. Write your code into the code editor, or copy and paste it from your favourite IDE. Your code should be laid out as a standard JavaScript script, for example:

const greeting = "Hello, World!";

if (greeting === "Hello, World!") {
  return greeting;
}

The following documentation will address axiom.ai-specific features, and limitations, that apply to your JavaScript scripts.

# Defining functions


Function use is available in your JavaScript scripts and can be helpful when handling complex scripts. For example:

const data = [scrape-data];

function evaluate(item1, item2) {
  return item1 === item2;
}

const duplicate = evaluate(data[0][0], data[1][0]);
if (duplicate) {
  console.log(`${data[0][0]} is a duplicate of ${data[1][0]}`);
}

# Using data tokens


Combining JavaScript with your data tokens allows you to combine the best of both worlds. Click "Insert data" and select your token to get started. All tokens are formatted as 2D arrays, but if there is only a single data point, it'll be a string. Tokens can be manually inserted. Axiom.ai will automatically parse data tokens that are placed inside of your code, just like any other step!

const data = [scrape-data];
return data[0];

# Arrays


When using a token containing multiple rows of data, such as [scrape-data] in your code, it will be replaced with the value of a token from a previous step in 2D array format, if it exists within your automation. For example:

const data = [scrape-data];
console.log(data);

// Output: [["A", "B", "C"], ["D", "E", "F"]]

# Strings


When a token contains a single value, this will be replaced with a single strong. For example:

const data = '[scrape-data]';
console.log(data);

// Output: "A"

# Manipulating data tokens


Once a token is converted to a variable in JavaScript, you can manipulate that data as you see fit. For example:

let data = [scrape-data];
data[0][1] = "X";
console.log(data);

// Original: [["A", "B", "C"], ["D", "E", "F"]]
// Output: [["A", "X", "C"], ["D", "E", "F"]]

# Returning data tokens


Any created or modified variables can be returned to be used in future steps. Arrays must be returned in 2D array format, whereas strings and booleans can be returned as they are. For example:

let data = [scrape-data];
data[0][1] = "X";
return data;

// Original: [["A", "B", "C"], ["D", "E", "F"]]
// Returned: [["A", "X", "C"], ["D", "E", "F"]]

Or if you wish to return a string or boolean:

let data = [scrape-data];
data[0][1] = "X";
if (data[0][1] === "X") {
  return true;
}

return false;

// Original: [["A", "B", "C"], ["D", "E", "F"]]
// Returned: true

# Run in app


The "Run in app" option allows you to run your code within the axiom.ai desktop application rather than in the browser by default. This gives you access to additional functionality, such as:

  1. Using the Node.js filesystem API.
  2. Using the Puppeteer API.

"Run in app" is disabled by default. Disable this option to allow console.log() to produce outputs in your browser, enabling this will disable the console.log() functionality as the function is not running in the browser window.

# Use cases


There are a number of uses cases that the "Write Javascript" step can be used for, including those mentioned above. Let's dive into more specific examples.

# Send data to an API


If you need to extend to functionality of the Trigger webhook step, use JavaScript. The following example sends scrape data to an API and returns the response as the code-data data token to be used elsewhere within your automation:

const data = [scrape-data];

//This function will send a request to an endpoint
async function postData() {
   try {
      let response = await fetch('<API_ENDPOINT>', {
        method: 'POST', 
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      
      if (response.ok) {
        const result = await response.json();
        return [[JSON.stringify(result)]];
      } else {
        console.error("Error:", response.status, response.statusText);
      }
    }
    catch (error) {
        console.error(error)
        return error
    }
}

return postData();

# Use Puppeteer's API


You can use Puppeteer's API within the "Write JavaScript" step. Run in app must be enabled to use this API.

Check out our Puppeteer documentation for more details.

# Use the Node.js filesystem API


You can use the Node.js filesystem api (fs) within the "Write JavaScript" step to access files on your local PC. Run in app must be enabled to use this API.

Note, axiom.ai uses promises in its javascript step, while fs uses callbacks. It's recommended that any fs functions are wrapped in promises, for example:

let result = await new Promise(resolve => {
  fs.readFile('/Users/joe/test.txt', 'utf8', (err, data) => {
    if (err) {
      resolve([[err.message]])
    } else {
      resolve([[data]])
    }
  });
})
return result

You can learn more about this API in the Node.js official documentation (opens new window).

# Use ChatGPT


In addition to the Extract data with Chatgpt step and Generate text with ChatGPT step, ChatGPT prompts can also be sent with JavaScript. Run in app must be enabled to use this API.

const key = '<API_KEY>'
const prompt = 'Write a short introduction to automation software.'

let result = await chatGPT(key, prompt);
return [[result]];

To learn more about obtaining an OpenAI API key, visit your OpenAI Account (opens new window)