在节点 js 模块中运行 newman

Runing newman inside of nodejs module

我有一个带有 class.

的 nodejs 模块

在 class 里面有一个调用 newman 的方法(Postman cli 运行ner)

无法弄清楚如何 return newman 运行 结果数据。 newman 调用自身(在模块外)工作没有任何问题。

mymodule.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