0

I want to get a variable from one .js file to another .js file. Right now I have main.js

const balances = require('./balance');
console.log(balances.balanceBTC)

and I have balance.js

const balanceBTC = () => {
  return arrayCleaned[0];
};
exports.balanceBTC = balanceBTC;

And I am getting the error

const balances = require('./balance');

ReferenceError: require is not defined

I am running this code via windows PowerShell and the node version is: v14.10.1

kgangadhar
  • 4,886
  • 5
  • 36
  • 54

2 Answers2

1

NodeJS might be treating your code as an ES Module. And CommonJS variables like "require" are not available in ES modules. Try one of the below:

  • As mentioned here, declare require before using it.

      import { createRequire } from 'module';
      const require = createRequire(import.meta.url);
    
      const balances = require('./balance');
      [...]
    
  • If you have "type" : "module" in your package.json, remove it

Vasan
  • 4,810
  • 4
  • 20
  • 39
-1

It looks like the problem is coming from the environment where you are running your code. Check the following links and you'lle find the answser:

Node | Require is not defined

https://www.thecrazyprogrammer.com/2020/05/require-is-not-defined.html

Require is not defined nodejs

https://github.com/nodejs/node/issues/33741

Christian LSANGOLA
  • 2,947
  • 4
  • 22
  • 36