Node Js course – 5 Require files

Hi,  for now the only way to run the project is directly from the app.js file and when we run the command “node app.js” in the terminal this will execute all the code that is in this file.

 But what happens if we need to run other files or other code that is in another file? so, for this question we need to use the “require()” method that is not part of standard Javascript API, but in Node.js  it’s a built-in function with special purpose that is to “load modules

So, I have the app.js file and the command that we are using in the terminal is “node app.js” this means that this file will be load, but also I have other file called utils.js so in the terminal I need to execute the same command “node app.js” – and what if I want to execute the “utils.js” file too?

For this we need to use the “require()” method in our app.js to import all the files into the app.js and in that way when we run in the terminal “node app.js” this will recognize all the files that are imported in the app.js, like this: 

utils.js file will be like this:

app.js file will be like this: 

But what about if I want to print a variable “lastName” that is in utils.js into “app.js” file, like this: 

and in our app.js we try to print: 

In this case we will have an error: 

An this error is because each file have it own scope, this mean that now app.js cannot access to the variables inside of other files even that file is required in the app.js file.

So, how can I have access to that variables from another file? well, we need to export all of the stuff that are in utils.js (or other file) to share with the outside world, to do this we take advantage of the another aspect of the module system which is “module.exports” and this is the part when we can define all the things that we want to share with other files. 

For example:

The module.exportst will be the return of this file, when the entire file will be required.

utils.js file: 

// Message to test utils.js file
console.log('utils.js file!');

const lastName = 'Rojas';

module.exports = lastName;

app.js file:

// Including other files 
const lastName = require('./utils.js');

console.log(lastName);

// Message to test app.js file
const name = 'Cristina';
console.log(name);

Exporting functions

Now if we have a function in the file utils.js (or other file) we can export this function and use that function into the app.js file:

utils.js file:

const add = function (a,b) {
  return a + b;
}

module.exports = add;

app.js file:

// Including other files 
const add = require('./utils.js');

const sum = add(4, -2); 

console.log(sum)

Result:

By Cristina Rojas.