I've been doing some reading on modularizing my code and decided to export some functions to a separate file and include them in my main function once it's called.
So I have two files, index.js and weather.js.
In my weather.js file I have :
"use strict";
exports.sometest = sometest;
function sometest() {
request('http://api.openweathermap.org/data/2.5/weather?&appid=' + process.env.weather_api_key + '', (error, response, body) => {
return body;
});
}
Then in my index.js file I include it const testing = require("../../../lib/weather");.
So how can I user the data I return within the function I've created? And could someone explain to me how it works, I'm a little confused in terms of scoping and syntax etc
Thank you.
I will first go through the details, then we will work down to answer your question. Its all about CommonJS standards. CommonJS standards specify the following three components when working with modules:
By now you should have gathered that we always require the module, if we were to use method 2 (exposing certain functionality) this is what it would look like:
//weather.js is the name of the file
exports.sometest = function() {
request('http://api.openweathermap.org/data/2.5/weather?&appid=' + process.env.weather_api_key + '', (error, response, body) => {
return body;
};
And then in your index file we would access this function like this:
const testing = require('../../../lib/weather.js');
// access the method from the 'testing' object
testing.sometest;
If you want to expose the full module:
// weather.js
module.exports = function sometest() {
request('http://api.openweathermap.org/data/2.5/weather?&appid=' + process.env.weather_api_key + '', (error, response, body) => {
return body;
});
};
In index.js it would look like this:
const testing = require("../../../lib/weather");
weatherTest = testing();
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With