Diola Oyeyele
Diola Oyeyele

Reputation: 63

How to use regular Javascript variables in Expressjs or Nodejs

Is there a way i can export variables from regular javascript to be used in expressjs?

i have tried using 'exports' but it didn't work.

for example in regular js file

var search ='hello';
exports= search;

then in express file

var search= require("./file.js");
console.log(search);

all i get in the console is '{}'.

What i want is for the variable 'search' to work in my express file as well. is there a way to do this

Upvotes: 2

Views: 168

Answers (3)

wc203
wc203

Reputation: 1217

You are doing it wrong. Here is the proper way of doing it:

Wrong way

var search ='hello';
exports= search;

Correct way

var search = 'hello';
exports.search = search;

To call it

var { search } = require('./file.js')
console.log(search)

I hope my answer was clear and good luck!

Upvotes: 1

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

Refer to exports shortcut in the docs:

The exports variable is available within a module's file-level scope, and is assigned the value of module.exports before the module is evaluated.

But it also says that:

However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.exports.

So when you do exports= search, it's not exported, only available in the module. To make it work, you just need to change it to module.exports = search.

Related: module.exports

Upvotes: 2

MarvinJWendt
MarvinJWendt

Reputation: 2684

Welcome to StackOverflow! To export a variable in file1:

var search = 'hello'
export search

// OR

export var search = 'hello'

To import it in file2:

import * as someName from './file1'
someName.search

// OR

var someName = require('./file1')
someName.search

Read more here: https://javascript.info/import-export

Upvotes: 0

Related Questions