Write to local file system using a postman collection

There are situations when you want to write the API response on local file system. So here I am explaining how to do that. Basically there are two ways to do it. One is by using node js scrip and another way to start a local server which accepts postman requests. Here I am explaining first method only.

  1. Ensure that you have node and npm installed.
  2. Install newman with: npm install newman.
  3. Create a file with the following contents:

var fs = require('fs'),
    newman = require('newman'),

    results = [];

newman.run({
    reporters: 'cli',
    collection: '/path/to/collection.json',
    environment: '/path/to/environment.json' // This is not necessary
})
.on('request', function (err, args) {
    if (!err) {
        // here, args.response represents the entire response object
        var rawBody = args.response.stream, // this is a buffer
            body = rawBody.toString(); // stringified JSON

        results.push(JSON.parse(body)); // this is just to aggregate all responses into one object
    }
})
// a second argument is also passed to this handler, if more details are needed.
.on('done', function (err, summary) {
    // write the details to any file of your choice. The format may vary depending on your use case
    fs.writeFileSync('migration-report.json', JSON.stringify(results, null, 4));
});

Here is another example:


var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // Body parser use JSON data

app.post('/launches', function(req, res) {

    var outputFilename = './spaceReport.json'; // path of the file to output

    fs.writeFileSync(outputFilename, JSON.stringify(JSON.parse(req.body.payload), null, 4)); // write to the file system

    res.send('Saved to ' + outputFilename);

});

var port = 3000;
app.listen(port);
console.log('Express started on port %d ...', port);

Leave a Reply

Your email address will not be published. Required fields are marked *