John Dews John Dews - 1 year ago 67
Node.js Question

Multiple Imports of the same dependency/service

I'm running into an issue with node, which could be adversely effecting the speed of my application.

Essentially my question is what is the proper way to use the same services/dependencies multiple places in my application.

For Example

// db.js File
Contains database connections and schema's

db = require("db.js")
users = require("user-route.js")
webhooks = require("webhooks-route.js")
andOthers = require("andOthers-route.js")

// *-route.js represents all route files
db = require("db.js")

As you can see each route imports db.js Does this effect performance, and if so how do you avoid doing this?

Answer Source

Multiple requires of the same module are cached. In other words, the first time "db.js" is required, it will be loaded and evaluated, and the resulting module object is cached in memory.

Subsequent calls to require("db.js") will just return the already-cached JS object.

This is documented here: Node.js Modules - Caching.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download