Require is a statement that Node interprets as, in some sense, a getter
function. For example, say you have a file named analysis.js
, and the inside of your file looks like this,
function analyzeWeather(weather_data) {
console.log('Weather information for ' + weather_data.time + ': ');
console.log('Rainfall: ' + weather_data.precip);
console.log('Temperature: ' + weather_data.temp);
//More weather_data analysis/printing...
}
This file contains only the method, analyzeWeather(weather_data)
. If we want to use this function, it must be either used inside of this file, or copied to the file it wants to be used by. However, Node has included a very useful tool to help with code and file organization, which is modules.
In order to utilize our function, we must first export
the function through a statement at the beginning. Our new file looks like this,
module.exports = {
analyzeWeather: analyzeWeather
}
function analyzeWeather(weather_data) {
console.log('Weather information for ' + weather_data.time + ': ');
console.log('Rainfall: ' + weather_data.precip);
console.log('Temperature: ' + weather_data.temp);
//More weather_data analysis/printing...
}
With this small module.exports
statement, our function is now ready for use outside of the file. All that is left to do is to use require()
.
When require
'ing a function or file, the syntax is very similar. It is usually done at the beginning of the file and set to var
's or const
's for use throughout the file. For example, we have another file (on the same level as analyze.js
named handleWeather.js
that looks like this,
const analysis = require('./analysis.js');
weather_data = {
time: '01/01/2001',
precip: 0.75,
temp: 78,
//More weather data...
};
analysis.analyzeWeather(weather_data);
In this file, we are using require()
to grab our analysis.js
file. When used, we just call the variable or constant assigned to this require
and use whatever function inside that is exported.