Fail to load package "randexp"

Hi,

I try to use the lib randexp but I fail to load in Postman pre-script.

I have tried using CDN:

pm.sendRequest("https://cdn.jsdelivr.net/npm/[email protected]/lib/randexp.min.js", (err, res) => {

    //convert the response to text and save it as an environment variable
    pm.collectionVariables.set("library", res.text());

    // eval will evaluate the JavaScript code and initialize the min.js
    eval(pm.collectionVariables.get("library"));

    console.log( new RandExp(/hello+ (world|to you)/).gen() );
})

which give an error

TypeError: Cannot read properties of undefined (reading 'text')

I also tired the variable method

var library = pm.collectionVariables.get('library');
 
// Invoke an anonymous function to get access to the dayjs library methods
(new Function(library))();
 
console.log( new RandExp(/hello+ (world|to you)/).gen() );

Error message

ReferenceError: RandExp is not defined

Am I missing something ?

PS.
I also find that there is a offical collection, which is also not working

Hi @lamricky11. Welcome to the Postman Community.

I’m not very certain what the issue could be here, but it appears that the library you’re trying to import isn’t minified. Sending a quick GET request to “https://cdn.jsdelivr.net/npm/[email protected]/lib/randexp.min.js”, I see that it is unminified.

Hi @gbadebo-bello, thank you for the reply.

Does unminified cause a problem ?

I also tried in the variable method, using this minified version, which it also not working. Is it because the lib is expoting a Class instead of a function?

Hey @lamricky11!

The code served by the CDN is not bundled, which is likely causing this issue as RandExp internally uses ret and drange packages.

I couldn’t find a CDN that provides the bundled version for RandExp but their repository has one. You can try the below snippet and use the lib as required:

const window = {};
eval((await pm.sendRequest("https://raw.githubusercontent.com/fent/randexp.js/refs/tags/v0.5.3/build/randexp.min.js")).text());
const RandExp = window.RandExp;

console.log(new RandExp(/hello+ (world|to you)/).gen());
2 Likes

It acutally work!! Thank you @appurva21 .

Is const window = {}; necessary for any package?

@lamricky11 It depends on how the package is bundled.

In some cases, you get a function that can be directly used, while in this case, if you closely look at randexp.min.js, it assigns RandExp to the global window object, which does not exist in Postman’s scripting environment.

image

Hence the const window = {} workaround to make the required code accessible.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.