bbbmazon
bbbmazon

Reputation: 75

Node use variables from another file

I have long list of variables at the beginning of my single file app. How can I move variables to another file and use them from there. Can I do that without requiring them as modules?

My code is written like this so I need variables to work just like the would be in the same file.

const1 = 'apple'
const2 = 'banana'
const3 = 'pear'
…

let1 = const1

console.log(let1)

and that should output apple.

And I want move those const variables from top

Help would be much appreciated!

Upvotes: 0

Views: 91

Answers (2)

LouMaster
LouMaster

Reputation: 21

You have to export the variable in vars.js

let const1 = 'apple'
exports.const1 = const1;

And then access via:

var request = require(./vars.js);
...
let x = request.const1;

Hope it helps!

Upvotes: 1

Renzo Calla
Renzo Calla

Reputation: 7696

It isn't a good practice but you can declare the variables as properties of the global object...

global.const1 = 'apple'
global.const2 = 'banana'
global.const3 = 'pear'
…

let1 = global.const1

console.log(let1)

Upvotes: 0

Related Questions