# How to set postman variable from node js

**URL:** <https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020>\
**Category:** Help Hub\
**Tags:** newman-project, json\
**Created:** [October 9, 2023, 1:53pm UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020 "2023-10-09T13:53:30Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![shalaka-m](https://avatars.discourse-cdn.com/v4/letter/s/c0e974/32.png) [@shalaka-m](https://community.postman.com/u/shalaka-m)\
**Post date:** [October 9, 2023, 1:53pm UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020/1 "2023-10-09T13:53:30Z")

</div>

Hi,  
I am using newman as library to run postman collections.  
Looking to do a validation to compare expected json response saved in json file while the responses are recived using on(‘request’,(error,data) event.

below is my code where content is response from api and data is json response in file.

```auto
data.item.events.members[0].script.exec = ["pm.test(\"compare Response Static values\", function () {\r",
                //data.item.events.members[0].script.exec = ["pm.test(\"compare Response Static values\", function () {\r",
                "pm.globalVariables.set(\"actresponse\",JSON.parse(content));\r",
                "pm.globalVariables.set(\"expresponse\",JSON.parse(data));\r",
                "pm.expect(pm.globalVariables.get(actresponse)).to.be.eql(pm.globalVariables.get(expresponse));\r","});"]

```

but I see below error when I execute :  
Cannot read properties of undefined (reading ‘set’) at assertion:0 in test-script.

questions : how can I pass node js variable to postman script?

Please help!

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [October 9, 2023, 3:15pm UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020/2 "2023-10-09T15:15:42Z")

</div>

Hey @shalaka-m 👋

Welcome to the Postman Community! :postman:

I’m really following what you’re trying to do here? What’s the Collection doing if you’re also trying to use the Newman events to make assertions against?

Might be just me - I’m just not really understanding the problem you’re trying to solve. 🤔

Can you also share your full script, please?

---

<div class="post-metadata">

**Author:** ![shalaka-m](https://avatars.discourse-cdn.com/v4/letter/s/c0e974/32.png) [@shalaka-m](https://community.postman.com/u/shalaka-m)\
**Post date:** [October 9, 2023, 3:32pm UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020/3 "2023-10-09T15:32:06Z")

</div>

Hi Danny,

Collection is hitting all the api’s and I am saving response in ‘actresponse’ variable.  
Then I am comparing it with response saved in file and stored in variable ‘expresponse’.

below is my complete script.

```auto
const newman = require('newman'); // require newman in your project
//const fs = require('fs');
const fs = require('fs/promises');
const { request } = require('http');
//const { error } = require('console');
//const htmlextra = require('newman-reporter-htmlextra');

// call newman.run to pass `options` object and wait for callback
newman.run({
    collection: require('./Test.postman_collection.json'),
    environment: require('./FecthData-QA-115.postman_environment.json'),
    reporters: 'cli'
}, function(err) {
    if (err) {
        throw err;
    }
}).on('request',(error,data)=>{
    //console.log('Request name:' + data.item.name);
    //console.log(data.response.stream.toString());
    let reqName = data.item.name;
    fileName = reqName+'_response.json';
    const content = data.response.stream.toString();
    let expresponse;
    let actresponse = JSON.parse(content);

    /*fs.readFile(fileName,'utf8', (error, data)=> {
        if (error){
            console.log(error);
        }
        //console.log("inside readFile");
        //console.log(fileName);
        //console.log(data);
        expresponse = JSON.parse(data);
        //console.log(expresponse);
        //console.log(array[0].date);
        //data.events[0].script.exec = ["pm.collectionVariables.set(\"expectedResponse\",array);"];
        //console.log(pm.collectionVariables.get("expectedResponse"));
        let actresponse = JSON.parse(content);
        
    
    });*/
    fs.readFile(fileName)
    .then((data)=>{
        expresponse = JSON.parse(data);
    })
    .catch((error)=>{
        console.log(error);
    })

    data.item.events.members[0].script.exec = ["pm.test(\"compare Response Static values\", function () {\r",
                //data.item.events.members[0].script.exec = ["pm.test(\"compare Response Static values\", function () {\r",
                "pm.globalVariables.set(\"actresponse\",JSON.parse(content));\r",
                "pm.globalVariables.set(\"expresponse\",JSON.parse(data));\r",
                "pm.expect(pm.globalVariables.get(actresponse)).to.be.eql(pm.globalVariables.get(expresponse));\r","});"];

});

```

---

<div class="post-metadata">

**Author:** ![xk0der](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/xk0der/32/2056_2.png) [@xk0der](https://community.postman.com/u/xk0der)\
**Post date:** [October 10, 2023, 10:31am UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020/4 "2023-10-10T10:31:20Z")

</div>

Hey @shalaka-m I spotted some issues which are likely the cause of errors you are seeing

The following code will run asynchronously, so it is not guaranteed that the value inside `expresponse` would be available when you are setting the script using `data.item.events.members[0].script.exec`

To fix this, move that statement inside `then()`.

And while setting global variables, you are passing strings, so `newman` would not be aware of what the variables `content` and `data`

```auto
...
"pm.globalVariables.set(\"actresponse\",JSON.parse(content));\r", // Where is content in the scope of the test script?
"pm.globalVariables.set(\"expresponse\",JSON.parse(data));\r", // same with data?
...

```

Change that to:

```auto
   data.item.events.members[0].script.exec = ["\n pm.test(\"compare Response Static values\", function () {\n",
   "pm.globalVariables.set('actresponse', '" + JSON.stringify(actresponse) + "');\n",
   "pm.globalVariables.set('expresponse', '" + JSON.stringify(expresponse) + "');\n",
   "pm.expect(JSON.parse(pm.globalVariables.get('actresponse'))).to.be.eql(JSON.parse(pm.globalVariables.get('expresponse')));\n","});"];

```

I haven’t tested these, but the async file-read function may cause other problems too! The code may not return before the collection’s “test” script gets executed for example.

You may want to revisit how you are structuring the file read to get expected responses. A better approach would be to read the responses and store inside a variable before executing `newman.run()`, but it would come at the cost of memory overhead.

---

<div class="post-metadata">

**Author:** ![shalaka-m](https://avatars.discourse-cdn.com/v4/letter/s/c0e974/32.png) [@shalaka-m](https://community.postman.com/u/shalaka-m)\
**Post date:** [October 17, 2023, 9:33pm UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020/5 "2023-10-17T21:33:36Z")

</div>

> [@xk0der](#):
>
> `(JSON.parse`

Thanks @xk0der ,  
I see this error using above solution ‘TypeError: Cannot read properties of undefined (reading ‘events’)’ .  
Looks like postman script is unable to read variables that are set in node.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [November 16, 2023, 9:34pm UTC](https://community.postman.com/t/how-to-set-postman-variable-from-node-js/53020/6 "2023-11-16T21:34:10Z")

</div>

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