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);
});
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.
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
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.
This demo code will work Save as
demo.jsUsing this demo collection
Save as
1-demo.postman_collection.jsonCollection structure
First Get Call
Second Get Call
Third Get Call
Install dependencies
Run it
Result
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.
1_response_2024-03-08_12-54-59_448.json2_response_2024-03-08_12-54-59_448.json3_response_2024-03-08_12-54-59_448.json