Use require() (or other method) in Nodejs as in PHP

Asked

Viewed 581 times

2

In PHP

Suppose I have a constant 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, called 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 define in the file index php. a constant, which was passed to the archive const.php and which was used to define another constant based on its value (CONST_1).
  • We call the constant CONST_1 back to the archive index php., without any kind of export in the file of its origin.

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 don’t know how to do that, given that:

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

The question

I can do, in Nodejs, what I did with PHP (in the example above), without having to create functions and pass parameters in them?

1 answer

1


Node.js uses modules 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);
  • Yap. So far I have. The problem is when I have a file that is not necessarily a module. The only way to import a Javascript file in the context of Node is by module.exports and require() (considering the file as a module)? I don’t really like the idea of encapsulating my entire file in one function just to run it in others.

  • This is the right and recommended way. There is always the option to read the disk file using the standard Node library for this, and to give an Eval in this file. With a similar operation you can also rewrite the file and turn it into a module, and from there use the require.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.