0

If I import a js file like this :

const importedFile = require( './file1');

I can see all my functions and console logs of file1 running, but I can't run or use a specific variable

If I console.log( importedFile ) I get this : {} empty object !

How to get all variables from file1.js ?

6
  • you cannot change const value Commented Dec 9, 2019 at 11:18
  • Noone is trying to change. just to read.. Commented Dec 9, 2019 at 11:20
  • Have a read about it here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 9, 2019 at 11:21
  • @DarrenSweeney — That's ES6 imports, not the Node module system. Commented Dec 9, 2019 at 11:23
  • From that link I tried this: import * as importedFile from './file1.js'; Gives me this: SyntaxError: Unexpected token * Commented Dec 9, 2019 at 11:29

2 Answers 2

2

JavaScript modules are self-contained environments with their own scope.

Only explicitly exported values are available outside of the module.

So, if you want something in ./file1 to be available in importedFile, then you need to include it in the exports:

const value = "Hello, world";

function thisIsAFunction() {
    console.log(value);
}

module.exports = {
    thisIsAFunction
}

Then you can:

const importedFile = require( './file1');
importedFile.thisIsAFunction();
Sign up to request clarification or add additional context in comments.

9 Comments

Yes I was able to import one variable, but as I said I can see everything running, but I can't use anything, why is that? Is there any way to export all variables ?
No. You can't export variables, only values.
Yeah all variable values, all together, not just one. And another problem is that in file1 my variables values change every 10 secs, but when I try to import I get only the first value
As I said, you can only export values, not variables. You can export a function that gives you their current values on demand. And you can put as many values in the object you export as you like.
Ah okay, but if the ' const value = "Hello, world"; ' was declared inside the function, how to read it then? Cause I need to read/use not just console.log it
|
0

I figured it out, in file1 I can export variables like this :

function thisIsAFunction() {
    let var1 = { qty: 123 }
    let var2 = { qty: 123 }
    let var3 = { qty: 123 }

    return [ var1, var2, var3 ];
}
module.exports = {
    thisIsAFunction
}

Then read/use the first variable like this:

let importedValue= importedFunct.thisIsAFunction()

console.log(  importedValue[0][0].qty)

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.