1

I'm using Javascript without HTML, just JavaScript with Node and I need some other js files so it does not take up too much space on the main file. And I was looking for, and I found something like "module.exports", but I did not understand it so well, can anyone explain this to me?

I've tried this

var xgr = require("./xgr.js").randomString;
randomString();

In the other file

function randomString() {
	var carac = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var rand = Math.floor(Math.random() * carac.length);
	var gerado = carac[rand];
	return gerado;
}

module.exports = randomString;

8
  • 5
    It should be xgr() instead of randomString() because that is the name you gave to the function when you've imported it. Commented Apr 26, 2017 at 14:37
  • sitepoint.com/understanding-module-exports-exports-node-js take a look at this. Explains it well. Commented Apr 26, 2017 at 14:38
  • 2
    @JasonKrs What part of "without HTML" and "node" did you have trouble understanding? Commented Apr 26, 2017 at 14:40
  • 1
    @torazaburo I don't think OP said "without node"... Commented Apr 26, 2017 at 14:41
  • 1
    That first comment is not quite right, see the bottom of the answer by @T.J. Crowder Commented Apr 26, 2017 at 14:42

2 Answers 2

6

The Node documentation on modules goes into this in a fair amount of detail.

Essentially, exports (also available as module.exports) is a predefined object in a module you can add properties to that you want to export. (Or you can replace the whole thing if you prefer.)

require retrieves the exports of the file you require.

So if a.js is:

exports.foo = function() {
    console.log("Hi there");
};

and b.js has

var a = require("./a");

then

a.foo();

...outputs "Hi there".


With your example xgr.js:

function randomString() {
    var carac = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var rand = Math.floor(Math.random() * carac.length);
    var gerado = carac[rand];
    return gerado;
}

module.exports = randomString;

you're replacing exports entirely. You'd use it like this:

var randomString = require("./xgr.js");

console.log(randomString());
Sign up to request clarification or add additional context in comments.

Comments

0

That's a good way to share your functions between components

var _public = exports;
_public.randomString = function () {
    let carac = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let rand = Math.floor(Math.random() * carac.length);
    let gerado = carac[rand];
    return gerado;
}

So you can use all your shared functions like this

let xgr = require("./xgr.js");
xgr.randomString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.