在NodeJS模块中运行Newman

人气:731 发布:2022-10-16 标签: node.js node-modules newman

问题描述

我有一个NodeJS模块和一个类。

类内部有一个调用Newman(Postman Cli Runner)的方法

想不出如何返回Newman运行结果数据。 Newman调用本身(在模块外部)工作时没有任何问题。

mymode.js

var newman = require('newman');

module.exports =  function (collection, data) {
    this.run = function () {

        newman.run({
            collection: require(this.collection + '.postman_collection.json'),
            environment: require(this.environment + '.postman_environment.json')
        }, function () {
            console.log('in callback');
        }).on('start', function (err, args) { 

        }).on('beforeDone', function (err, data) { 

        }).on('done', function (err, summary) {

        });

        return 'some result';
    }
}

index.js


var runNewman = require('./mymodule');

var rn = new runNewman(cName, cData);

var result = rn.run(); // never returns any variable
cosole.log(result); 

推荐答案

您可以看到newman使用事件和回调。如果您需要数据,则需要从done事件回调中发送数据。您可以在此处执行的操作是将代码转换为使用Promise api

参考下面的代码片段

var newman = require('newman')

module.exports = function (collection, data) {
  this.run = function () {
    return new Promise((resolve, reject) => {
      newman.run({
        collection: require(this.collection + '.postman_collection.json'),
        environment: require(this.environment + '.postman_environment.json')
      }, function () {
        console.log('in callback')
      }).on('start', function (err, args) {
        if (err) { console.log(err) }
      }).on('beforeDone', function (err, data) {
        if (err) { console.log(err) }
      }).on('done', function (err, summary) {
        if (err) { reject(err) } else { resolve(summary) }
      })
    })
  }
}

为此调用代码

var runNewman = require('./mymodule');

var rn = new runNewman(cName, cData);

var result = rn.run().then(console.log, console.log); //then and catch

288