0

I have a node server. This is what my init file looks like:

require("variables");
require("constants");
require("index");

app.get('/', function (req, res, next) {
 res.sendFile(__dirname + '/index.html');
});

httpServer.listen(port, () => {
 console.log(`server running`);
});  

My variables file looks like this:

file = "file.json";
dataopen = "stuff";
userdata = "user";

module.exports={file,dataopen,userdata}

whereas my constants file:

const button = "<div></div>";
const title = "Page Title";
const input = "submit";

module.exports={button,title,input}

The thing here is that if I call for a variable inside index.js it will read it just fine:

console.log(dataopen);  //it will output 'stuff'

but not so with any constants which will output undefined unless I include this line on top:

const { button,title,input } = require("constants");

Why is that? Why do I need the extra line for constants but not for variables as well? I also noticed that by removing the prefix const before declaring then I won't need the line, but why is that?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cain Nuke
  • 2,843
  • 5
  • 42
  • 65
  • Does this answer your question? [In what scope are module variables stored in node.js?](https://stackoverflow.com/questions/15406062/in-what-scope-are-module-variables-stored-in-node-js) – Phil Mar 09 '23 at 01:57

1 Answers1

1

Do a console.log(global). Chance are that you will see your dataopen and the other vars.

In a nutshell, by not "declaring" a variable, it will implicitly be global. And when you try to access an undeclared variable, js regards it is a global variable. Something that is not allowed anymore in strict mode.

Should not be said, but global vars bad, do not use them.

Federkun
  • 36,084
  • 8
  • 78
  • 90
  • Thanks. What about functions? – Cain Nuke Dec 25 '22 at 22:38
  • Same for functions. If you are coming from php, the `require` aka "let me dump the source code of this file here" works differently from the `require`-commonjs module. It may help if you search for a naive implementation of commonjs's require to get an idea – Federkun Dec 25 '22 at 22:43