By Shivam Singh, founder of TesterRank · Updated September 2026
So far you have used Newman as a CLI tool. But Newman is also a Node.js module. You can require() it and run collections programmatically. Why would you? When you need custom logic around your test runs — dynamic collection selection, custom reporters, parallel execution, integration with other tools.
Newman can also be used from your own JavaScript file. This gives you full control, such as running several collections or sending results somewhere after the run.
// run-tests.js
const newman = require('newman');
newman.run({
collection: require('./collections/api-tests.postman_collection.json'),
environment: require('./environments/staging.postman_environment.json'),
reporters: ['cli', 'htmlextra'],
reporter: {
htmlextra: {
export: './reports/api-report.html',
title: 'API Test Report',
darkTheme: true
}
}
}, function (err, summary) {
if (err) {
console.error('Newman run encountered an error:', err);
process.exit(1);
}
console.log('Collection run complete!');
console.log(`Total requests: ${summary.run.stats.requests.total}`);
console.log(`Failed requests: ${summary.run.stats.requests.failed}`);
console.log(`Total assertions: ${summary.run.stats.assertions.total}`);
console.log(`Failed assertions: ${summary.run.stats.assertions.failed}`);
if (summary.run.failures.length > 0) {
console.log('\nFailed tests:');
summary.run.failures.forEach(failure => {
console.log(` - ${failure.error.test}: ${failure.error.message}`);
});
process.exit(1);
}
});Run the file with Node like any other script.
# Run it
node run-tests.jsPass the same options you would use on the command line, such as environment, data file and reporters, as an object.
// run-with-options.js
const newman = require('newman');
newman.run({
collection: './collections/api-tests.postman_collection.json',
environment: './environments/staging.postman_environment.json',
iterationData: './data/test-data.csv',
iterationCount: 10,
delayRequest: 500,
timeoutRequest: 10000,
bail: true,
insecure: true, // Same as -k flag
folder: 'Auth',
reporters: ['cli', 'junit'],
reporter: {
junit: {
export: './reports/junit-results.xml'
}
},
envVar: [
{ key: 'authToken', value: process.env.AUTH_TOKEN },
{ key: 'apiKey', value: process.env.API_KEY }
]
}, (err, summary) => {
if (err) throw err;
console.log('Done. Failures:', summary.run.failures.length);
});The programmatic API lets you listen to events during the run — before each request, after each request, when a test fails, etc. This is powerful for custom reporters and logging.
// events-example.js
const newman = require('newman');
const run = newman.run({
collection: require('./collections/api-tests.postman_collection.json'),
reporters: ['cli']
});
// Fires before each request
run.on('beforeRequest', function (err, data) {
if (err) return;
console.log(`Sending: ${data.request.method} ${data.request.url}`);
});
// Fires after each request completes
run.on('request', function (err, data) {
if (err) return;
const status = data.response.code;
const time = data.response.responseTime;
console.log(`Response: ${status} (${time}ms)`);
});
// Fires when an assertion passes or fails
run.on('assertion', function (err, data) {
if (err) {
console.error(`FAIL: ${data.assertion} — ${err.message}`);
} else {
console.log(`PASS: ${data.assertion}`);
}
});
// Fires when the entire run completes
run.on('done', function (err, summary) {
if (err) return console.error(err);
console.log(`\nRun complete. ${summary.run.stats.assertions.failed} failures.`);
});Need to run three collections in sequence? With the CLI you chain commands. With the library you have full control — run them in parallel, handle failures individually, aggregate results.
// run-multiple.js
const newman = require('newman');
const path = require('path');
const collections = [
{ name: 'Auth Tests', file: 'auth-tests.postman_collection.json' },
{ name: 'User Tests', file: 'user-tests.postman_collection.json' },
{ name: 'Order Tests', file: 'order-tests.postman_collection.json' }
];
const environment = './environments/staging.postman_environment.json';
let totalFailures = 0;
function runCollection(config) {
return new Promise((resolve, reject) => {
newman.run({
collection: path.join('./collections', config.file),
environment: environment,
reporters: ['cli']
}, (err, summary) => {
if (err) return reject(err);
const failures = summary.run.failures.length;
totalFailures += failures;
console.log(`${config.name}: ${failures} failures`);
resolve(summary);
});
});
}
// Run all collections sequentially
async function main() {
for (const col of collections) {
await runCollection(col);
}
console.log(`\nTotal failures across all collections: ${totalFailures}`);
process.exit(totalFailures > 0 ? 1 : 0);
}
main();The programmatic API returns the same summary object you see in the CLI output — but as structured data. You can send failure counts to Slack, save metrics to a database, or trigger rollbacks based on results. The possibilities open up once you treat Newman as a library, not just a CLI.
Q: When would you use Newman as a Node.js library instead of the CLI?
A: Use the library when you need: 1) Custom logic — dynamically select which collection to run based on branch name or deployment target. 2) Aggregated results — run multiple collections and combine results into a single report. 3) Event-driven actions — send a Slack notification when a specific test fails, not just at the end. 4) Custom reporters — listen to events and format output however you need. 5) Integration with test frameworks — wrap Newman runs inside Mocha or Jest test suites. The CLI is great for simple, straightforward runs. The library is for when you need programmatic control.
Key Point: Newman as a library gives you programmatic control — event listeners, custom logic, parallel runs, and integration with other Node.js tools.