【问题标题】:Runing newman inside of nodejs module在节点 js 模块中运行 newman
【发布时间】:2019-10-16 14:08:28
【问题描述】:

我有一个带有类的 nodejs 模块。

类里面有一个调用newman(Postman cli runner)的方法

无法弄清楚如何返回 newman 运行结果数据。 newman 调用本身(在模块之外)可以正常工作。

我的模块.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); 

【问题讨论】:

    标签: node.js node-modules newman


    【解决方案1】:

    如您所见,newman 使用事件和回调。如果您想要数据,您需要从done 事件回调中发送数据。您可以在这里做的是将您的代码转换为使用Promise api

    参考下面的sn-p

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      相关资源
      最近更新 更多