Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using exports in nodejs to return a value

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.

like image 810
pourmesomecode Avatar asked Mar 20 '26 20:03

pourmesomecode


1 Answers

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:

  1. require(): This method is used to load a module into your code.
  2. exports: This object is contained in each module and allows to expose certain functionality of your code when the module is loaded using require().
  3. module.exports: Exposes the full module when it is loaded using require().

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!