Enrique Foleman
Enrique Foleman

Reputation: 13

Is there a way to load specific modules in nodejs?

I'm creating an application with NodeJS and I would to like to import just certain parts of my own modules, so I can load the other parts later (it's to improve performance and not having to load all my modules in memory). For example:

test.js

const foo = () => {
    //something
    return x
}
const bar = () => {
    //something
    return y
}

module.exports.someFunc = foo
module.exports.otherFunc = bar

So, if I import in app.js like this:

app.js

const a = require('./test').someFunc

Is node just loading someFunc from test.js? Or, does it load the whole script with both of the functions in the cache?

I googled a lot, but I couldn't find a proper answer.

Upvotes: 1

Views: 419

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Is node just loading someFunc from test.js? Or, does it load the whole script with both of the functions in the cache?

The latter. If the module isn't already loaded, its full file is loaded and executed (with all the side effects), and the resulting exports object is cached. Then you get a reference to the module's exports object, and then your code takes someFunc from it.

This is a current limitation of the Node module system. If you want those to be separate, you need to separate them (and then perhaps create a module whose job is to load both of them, for code that already uses the full module), e.g.:

foo.js:

const foo = () => {
    //something
    return x
};
exports = foo;

bar.js:

const bar = () => {
    //something
    return y
};
exports = bar;

..and then perhaps test.js:

const foo = require("./foo.js");
const bar = require("./bar.js");

module.exports.someFunc = foo;
module.exports.otherFunc = bar;

Upvotes: 1

Related Questions