How to call a file in node.js

2

I want to know how I call a .js file if anyone can explain step by step thank you.

As far as I understand to call an external file I have to create a sort of package that proceeds?

    
asked by anonymous 20.01.2015 / 17:05

1 answer

8

For you to call your .js file you need to do so;

In .js file

module.exports = 'olá mundo'; //Você pode exportar qualquer coisa (não apenas uma string)

module is a global variable injected into all files by node, you can change the exports attribute of that variable to expose (make visible) the contents of your module. Everything that is not assigned to the module.exports property is private to the module and therefore not externally accessible.

And in your other file, app.js for example:

var arquivo = require('./arquivo.js'); //Desde que arquivo.js esteja na mesma pasta
console.log(arquivo);

The package you are referring to, ie the package.json is not required. It is optional but extremely recommended. When you further develop your knowledge I suggest that it should be the next thing to learn because it is with it that you manage the dependencies of your application with npm (among other things).

The variable require also did not come from "nothing", just like module it is a variable injected by the node that allows loading the contents of the module. If you point to a file .json the require will load the contents of this file for you (something very practical).

Every time you make a require of a module it is placed in a cache , ie if you make more than one require throughout your file your module is loaded only once so it is common that you find all "requires" at the beginning of the file, ie you do not need to call it repeated times for the same module.

Another example

in Animal.js

module.exports = function Animal(nome, tipo) {
    this.nome = nome;
    this.tipo = tipo;
}

in app.js

var Animal = require('./Animal.js'), //o '.js' é opcional! require('./Animal') também funcionaria
    peDePano = new Animal('Pé de Pano', 'Cavalo');

console.log(peDePano.tipo);

Another Example

In data.json:

{
    "site": "StackOverflow",
    "url": "pt.stackoverflow.com"
}

In app.js

var dados = require('./dados.json');
console.log(dados.site + ': ' + dados.url);
    
20.01.2015 / 17:09