How to call a file in Node.js

Asked

Viewed 4,198 times

1

I want to know what 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 kind of package that proceeds?

1 answer

8

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

In file.js

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 attribute exports of this variable to display (make visible) the contents of your module. Everything that is not assigned to the property module.exports is private to the module and therefore not accessible externally.

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 refer to, namely the package json. is not required. It is optional but is highly recommended. When you evolve a little more 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 the npm (among other things).

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

Every time you make a module require it is cached, that is, if you do more than one require along your file your module is loaded only once, so it is common that you find all "requires" at the beginning of the file, that is, you do not need to call it repeatedly for the same module.

One more 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);

Other Example

In data.json:

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

Em app.js

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

Browser other questions tagged

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