cannot require a module in JavaScript policy

Not applicable

I have a JavaScript policy that needs to require a Node.js module assert. The JavaScript file testAssert.js has the following code:

var assert = require('assert');
var transactionId = context.getVariable("transactionId");
var result = assert.equals(transactionId, "123");
print("test assert:" + result);

The following is the policy that invokes the JavaScript file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="retrievePointsHistory">
<DisplayName>retrievePointsHistory</DisplayName>
<Properties/>
<ResourceURL>jsc://testAssert.js</ResourceURL>
</Javascript>

It throws the following exception:

{
"fault": {
"faultstring": "Execution of retrievePointsHistory failed with error: Javascript runtime error: \"ReferenceError: \"require\" is not defined. (retrievePointsHistory.js:1)\"",
"detail": {
"errorcode": "steps.javascript.ScriptExecutionFailed"
}
}
}

It seems that a JavaScript policy cannot use "require". Any help is appreciated.

1 2 1,630
2 REPLIES 2

No, you cannot, see this thread https://community.apigee.com/questions/40104/can-we-add-nodejs-as-policy.html

However you can isolate the library you need into another JS file and include it into the policy via the <IncludeURL>jsc:...<IncludeURL> same as with the <ResourceURL>

YES. And you may also want to try browserify.

This won't work for all npm modules. Some of them use ES6 features that are not available for JS callouts.

JS callouts run in the Rhino engine, which does not support all the latest JavaScript features. See here for a list of compatible things.