node.js - 导出/导入Nightmare.js函数

标签 node.js nightmare

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

这些函数会被调用,但 Nightmare 函数实际上不会执行或引发错误。

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

我的主要应用程序:

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
        }
    }
}

我认为这与我的 Nightmare 实例没有导出/导入有关,但不确定如何执行此操作。

最佳答案

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'))

关于node.js - 导出/导入Nightmare.js函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301874/

相关文章:

javascript - 等待 Nightmare js中的javascript函数

node.js - 无法实例化扩展 EventEmitter 的导出自定义模块 Nodejs 的实例

node.js - 如何将 PassportJS 与 HapiJS 一起使用

php - 在php中调用node.js(nightmarejs)脚本

node.js - Nightmare js出现错误的导航错误?

javascript - Nightmare 没有从评估中返回正确的值

javascript - 使用cheerio获取所有包含的js

linux - 如何使用 cron 作业?

javascript - 使用 Angular 5 和 Node js 后端的 get 方法未正确发送多个参数

nightmare - Nightmare.js和IE兼容模式