Use require () (or another method) in NodeJS as in PHP

2

In PHP

Suppose I have a const file in a root directory called const.php :

define('CONST_1', BASE_CONST_1 || 'Value 1');
define('CONST_2', 'Value 2');
define('CONST_3', 'Value 3');

And another file, in the same directory, named index.php :

define('BASE_CONST_1', 'Valor que veio do índice';

require_once 'const.php';

echo CONST_1; // Iria aparecer na tela do usuário 'Valor que veio do índice'.

Emphasize above what happened:

  • We defined in the index.php file a constant that was passed to the const.php file and which was used to define another constant based on its value ( CONST_1 ).
  • We call the constant CONST_1 back to the index.php file, with no export type in the source file.
  

Obviously there is no logic in doing exactly as I did above, my goal was just to show what I can do in PHP.

No NodeJS

In NodeJS, I do not know a way to do this, given that:

  • Variables and constants are not passed to the file that we import ( in the same way as in the PHP example, the constant BASE_CONST_1 was passed to the const.php file.

The question

Can I make, in NodeJS, the same as I did with PHP (in the example above), without having to create functions and pass parameters in them?

    
asked by anonymous 10.01.2018 / 21:18

1 answer

1

Node.js uses modules that you can import. For example:

// modulo.js
module.exports = {
   'funcao' : function() { return 'função executada'; },
   'propriedade' : 10
}

// principal.js
const meuModulo = require('./modulo');
console.log(meuModulo.funcao());
console.log(meuModulo.propriedade);
    
10.01.2018 / 21:25