2

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.