0

Hallo I want to save file response every iterationData in newman library node js. In collection I have one request. This is my file.

const newman = require('newman');
const fs = require('fs');
      let today = new Date().toISOString().slice(0, 10)
      let time = Date.now();
      let jsonFile = './response.json'
newman.run({
    collection: require('./collection.json'),
    reporters: 'cli',
    iterationData: jsonFile,
    verbose: true
}).on('request', function (error, data) {
    if (error) {
        console.error(error);
        return; 
    }
    const requestname = data.item.name; 
    const filename = 'response_'+requestname+ '_' + today + '_' + time+'.json'; 
    const content  = data.response.json(); 
    fs.writeFile(filename, JSON.stringify(content), function (error) {
        if (error) { 
            console.error(error);
        }
    });
console.log('Request name: ' + data.item.name);
        });  

1 Answer 1

0

To make Newman's response human-readable, you must convert it from its raw format to a format that can be easily understood by humans.

This line creates a Buffer object from the binary data in response.stream.

Then, it decodes this binary data into a UTF-8 encoded string. Finally, it assigns the resulting human-readable text to the variable responseData.

const responseData = Buffer.from(response.stream).toString('utf8');

This code first constructs the absolute path to the directory where response files will be saved, appending it to the current directory (__dirname) followed by a subdirectory named 'responses'. If the directory doesn't exist, it creates it using fs.mkdirSync, ensuring the directory is available for saving response files

const responsesDir = path.join(__dirname, 'responses');
if (!fs.existsSync(responsesDir)) {
    fs.mkdirSync(responsesDir);
}

Filename structure

This code generates a filename for each response file based on the current date and time, along with the milliseconds component to ensure uniqueness. The structure of the filename includes:

The loop index incremented by 1 (index + 1) to start from 1 instead of 0. The string 'response' as a prefix. The current date in the format 'YYYY-MM-DD'. The current time in the format 'HH-MM-SS'. The milliseconds part of the current time. The file extension '.json' indicating it's a JSON file.

const today = new Date().toISOString().slice(0, 10); // Format: YYYY-MM-DD
const time = new Date().toISOString().slice(11, 19).replace(/:/g, '-'); // Format: HH-MM-SS
const milliseconds = new Date().getMilliseconds(); // Get milliseconds part of current time
const filename = `${index + 1}_response_${today}_${time}_${milliseconds}.json`;

This demo code will work Save as demo.js

const newman = require('newman');
const fs = require('fs');
const path = require('path');

const options = {
    collection: './1-demo.postman_collection.json',
};

newman.run(options, function (err, summary) {
    if (err) {
        console.error('Newman run encountered an error:', err);
        return;
    }

    console.log('Newman run completed successfully!');

    const responsesDir = path.join(__dirname, 'responses');
    if (!fs.existsSync(responsesDir)) {
        fs.mkdirSync(responsesDir);
    }

    // Process each executed request
    summary.run.executions.forEach(function (execution, index) {
        const request = execution.request;
        const response = execution.response;

        // Generate filename with custom format including request name, loop index, and milliseconds
        const today = new Date().toISOString().slice(0, 10); // Format: YYYY-MM-DD
        const time = new Date().toISOString().slice(11, 19).replace(/:/g, '-'); // Format: HH-MM-SS
        const milliseconds = new Date().getMilliseconds(); // Get milliseconds part of current time
        const filename = `${index + 1}_response_${today}_${time}_${milliseconds}.json`;

        // Check if response object is defined
        if (response && response.stream) {
            // Convert Uint8Array data to human-readable text
            const responseData = Buffer.from(response.stream).toString('utf8');
        
            // Parse the response data to JSON object
            let jsonResponse;
            try {
                jsonResponse = JSON.parse(responseData);
            } catch (error) {
                console.error(`Error parsing response data for response ${index + 1}:`, error);
                return;
            }
        
            const prettyJsonResponse = JSON.stringify(jsonResponse, null, 4);
        
            // Write the response data to a JSON file
            const filePath = path.join(responsesDir, filename);
            fs.writeFile(filePath, prettyJsonResponse, function (err) {
                if (err) {
                    console.error(`Error writing response data to file ${filename}:`, err);
                } else {
                    console.log(`Response data saved to ${filename}`);
                }
            });
        } else {
            console.error(`Error: No stream data found for response ${index + 1}`);
        }
    });
});

Using this demo collection

Save as 1-demo.postman_collection.json

{
    "info": {
        "_postman_id": "16eff56f-7d0d-461e-8075-a5d46aa2dc63",
        "name": "1-demo",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
        "_exporter_id": "1826150"
    },
    "item": [
        {
            "name": "Get Lion",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "exec": [
                            "var jsonData = JSON.parse(responseBody);\r",
                            "console.log(jsonData[0].name);\r",
                            "\r",
                            "pm.test('Animal = ' + jsonData[0].name, function () {\r",
                            "    pm.expect(jsonData[0].name).to.eql(\"Lion\");\r",
                            "});\r",
                            ""
                        ],
                        "type": "text/javascript"
                    }
                }
            ],
            "request": {
                "auth": {
                    "type": "noauth"
                },
                "method": "GET",
                "header": [],
                "url": {
                    "raw": "https://freetestapi.com/api/v1/animals?search=Lion",
                    "protocol": "https",
                    "host": [
                        "freetestapi",
                        "com"
                    ],
                    "path": [
                        "api",
                        "v1",
                        "animals"
                    ],
                    "query": [
                        {
                            "key": "search",
                            "value": "Lion"
                        }
                    ]
                }
            },
            "response": []
        },
        {
            "name": "Get Elephant",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "exec": [
                            "var jsonData = JSON.parse(responseBody);\r",
                            "console.log(jsonData[0].name);\r",
                            "\r",
                            "pm.test('Animal = ' + jsonData[0].name, function () {\r",
                            "    pm.expect(jsonData[0].name).to.eql(\"Elephant\");\r",
                            "});\r",
                            ""
                        ],
                        "type": "text/javascript"
                    }
                }
            ],
            "request": {
                "auth": {
                    "type": "noauth"
                },
                "method": "GET",
                "header": [],
                "url": {
                    "raw": "https://freetestapi.com/api/v1/animals?search=Elephant",
                    "protocol": "https",
                    "host": [
                        "freetestapi",
                        "com"
                    ],
                    "path": [
                        "api",
                        "v1",
                        "animals"
                    ],
                    "query": [
                        {
                            "key": "search",
                            "value": "Elephant"
                        }
                    ]
                }
            },
            "response": []
        },
        {
            "name": "Get Tiger",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "exec": [
                            "var jsonData = JSON.parse(responseBody);\r",
                            "console.log(jsonData[0].name);\r",
                            "\r",
                            "pm.test('Animal = ' + jsonData[0].name, function () {\r",
                            "    pm.expect(jsonData[0].name).to.eql(\"Tiger\");\r",
                            "});\r",
                            ""
                        ],
                        "type": "text/javascript"
                    }
                }
            ],
            "request": {
                "auth": {
                    "type": "noauth"
                },
                "method": "GET",
                "header": [],
                "url": {
                    "raw": "https://freetestapi.com/api/v1/animals?search=Tiger",
                    "protocol": "https",
                    "host": [
                        "freetestapi",
                        "com"
                    ],
                    "path": [
                        "api",
                        "v1",
                        "animals"
                    ],
                    "query": [
                        {
                            "key": "search",
                            "value": "Tiger"
                        }
                    ]
                }
            },
            "response": []
        }
    ]
}

Collection structure

enter image description here

First Get Call enter image description here

enter image description here

Second Get Call enter image description here

Third Get Call enter image description here

Install dependencies

npm install newman fs path

Run it

node demo.js

Result

enter image description here

The issue with the timestamp being the same is likely due to the rapid execution of the code within a short time frame. Since the timestamp is generated using the new Date() method, if the code runs multiple times within the same second, the timestamp won't change because the milliseconds component won't increment accordingly.

Adding the loop index prefix to the filename ensures that each file generated has a unique identifier.

enter image description here

1_response_2024-03-08_12-54-59_448.json

[
    {
        "id": 1,
        "name": "Lion",
        "species": "Panthera leo",
        "family": "Felidae",
        "habitat": "Grasslands and Savannas",
        "place_of_found": "Africa",
        "diet": "Carnivore",
        "description": "The lion is a large and powerful wild cat known for its majestic appearance and social behavior.",
        "weight_kg": 190,
        "height_cm": 120,
        "image": "https://fakeimg.pl/500x500/cc6601"
    }
]

2_response_2024-03-08_12-54-59_448.json

[
    {
        "id": 2,
        "name": "Elephant",
        "species": "Loxodonta africana",
        "family": "Elephantidae",
        "habitat": "Savannas, Grasslands, and Forests",
        "place_of_found": "Africa, Asia",
        "diet": "Herbivore",
        "description": "The elephant is the largest land animal on Earth and is known for its intelligence and long trunk.",
        "weight_kg": 6000,
        "height_cm": 300,
        "image": "https://fakeimg.pl/500x500/cc6602"
    }
]

3_response_2024-03-08_12-54-59_448.json

[
    {
        "id": 3,
        "name": "Tiger",
        "species": "Panthera tigris",
        "family": "Felidae",
        "habitat": "Forests, Grasslands, and Swamps",
        "place_of_found": "Asia",
        "diet": "Carnivore",
        "description": "The tiger is a powerful predator with striking orange fur and black stripes.",
        "weight_kg": 250,
        "height_cm": 100,
        "image": "https://fakeimg.pl/500x500/cc6603"
    }
]
1
  • @KamilSurma, Welcome, I happy to hear you got it, can you accept my answer. It will give me 15 points. (you need to click up arrow at my answer on left top)
    – Bench Vue
    Commented Mar 13 at 13:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.