【问题标题】:Export/Import Nightmare.js functions导出/导入 Nightmare.js 函数
【发布时间】:2019-04-05 18:30:01
【问题描述】:

所以,我有一个可运行的 nightmare.js 应用程序,它可以 100% 运行。我现在处于重构阶段,想将我制作的自定义函数(使用 nightmare.js 函数)放入另一个文件中,然后将它们导出/导入到我的主文件中。

函数被调用,但噩梦函数实际上并没有执行或抛出错误。

为什么噩梦功能在导入时不起作用?

我的主应用:

const Nightmare = require('nightmare')
const nightmare = Nightmare({
    show: true,
    typeInterval: 1000,
    waitTimeout: 60 * 1000
})

const bot = require('./utils')

nightmare
    .goto(url)
    .then(_ => bot.selectByVal('#myDiv', 'myVal'))
    .then( 'yada yada yada ...')...

module.exports = nightmare;

实用程序:

const Nightmare = require('nightmare');
const nightmare = Nightmare();

module.exports = {
    selectByVal: function(el, val) {
        console.log('select' + el + val)
        try {
            return nightmare.select(el, val)
        } catch (e) {
            return e
        }
    }
}

我认为这与我的噩梦实例没有被导出/导入有关,但不知道该怎么做。

【问题讨论】:

  • npm 包简直是噩梦?
  • 是的,nightmare.js 是一个用于网页自动化的 npm 包

标签: node.js nightmare


【解决方案1】:

botutils 无权访问在主应用程序上创建的 nightmare。您需要传递引用。

返回一个函数,而不是返回一个对象。

module.exports = function(nightmare) { // <-- now the same nightmare is in both file 
  return {
    selectByVal: function(el, val) {
      console.log('select' + el + val)
      try {
        return nightmare.select(el, val)
      } catch (e) {
        return e
      }
    }
  }
}

然后在您的主应用上,

const bot = require('./utils')(nightmare) // <-- pass the reference

nightmare
  .goto(url)
  .then(_ => bot.selectByVal('#myDiv', 'myVal'))

【讨论】:

猜你喜欢
  • 2017-05-07
  • 2017-02-23
  • 2021-09-18
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 2020-06-12
相关资源
最近更新 更多