I am trying to my API collection using newman as a library. Based on reference link below, i have created script (please find below snippet for the same) and trying to run my collection outside postman.
Reference Link : Postman: How to Write Files to Disk? | by Valentin Despa | APIs with Valentine | Medium
Code Snippet:
const newman = require('newman'),
fs = require('fs');
newman.run({
    collection: require('./postman_collection.json'),
	insecure: true,
	globals: require('./globals.json'),
	iterationData: require('./InputData.json'),
	folder: 'TC05',
    reporters: 'cli'
}).on('beforeRequest', function (error, args) {
    if (error) {
        console.error(error);
    } else {
        fs.writeFile(`./writeToFile/${args.item.name}-request.json`, args.request.body.raw, function (error) {
            if (error) { 
                console.error(error); 
            }
        });    
    }
}).on('request', function (error, args) {
    if (error) {
        console.error(error);
    }
    else {
		if(`${args.item.name}` == `genLetter`){
			fs.writeFile(`./writeToFile/${args.item.name}-response.docx`, args.response.stream, function (error) {
            if (error) { 
                console.error(error); 
            }
			});
		}
		else{
        fs.writeFile(`./writeToFile/${args.item.name}-response.json`, args.response.stream, function (error) {
            if (error) { 
                console.error(error); 
            }
        });        
    }
}
});
During run i see some / few of tests passed with scripts assertions written but for most of API requests its failing due to below error. Please find below snippet for errors.


On the other hand - i have also run my collection using newman cli commands (like using - g for globals, -d for data etc.) and all API steps in collection were passed. But i am using script approach because i wanted to save request and response for each API test step in my collection.
Can any one guide me in right direction on how i can overcome on this issue as i am consistently facing the issue as captured.