Beginning require use with a function and file
suggest changerequire is a function Node.js provides for loading a CommonJS module. 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.
To use the function from another file, export it. A function declaration is hoisted, so this module.exports can appear above the function. 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 requiring a file, the call usually sits near the top and is assigned to a const (or var) for the rest of the file. For example, handleWeather.js, in the same directory as analysis.js, looks like this:
const analysis = require('./analysis.js');
const 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.