Search code examples
javascriptnode.jsautomationnightwatch.js

How can I define variables that can be accessed from different files using node.js?


I am automating e2e scenarios using Cucumber, Nightwatch / node.js and javaScript.

I want to define variables than can be accessed from different .js files. Currently there are some variables defined in globals/globals.js file in the following format:

module.exports = {
    testVar: "testVariableDefinition",
}

Once defined I am accessing them through:

var test = this.api.globals.testVar;

So this means that I want to define other variables in a file different than globals.js and access them later. The reason behind this is that I cannot define all variables in one file, it is a little bit messy.


Solution

  • Since you've exported the variable, you could simply import or require it where you want to use.

    // Assuming fileA.js and fileB.js are in the same directory
    // fileA.js
    module.exports = {
      testVar: "testVariableDefinition",
    }
    
    // fileB.js
    const { testVar } = require('./fileA');