FizzyGalacticus
FizzyGalacticus

Reputation: 427

NPM Package local VS global scope

I've been having some issues with node, npm and trying to figure out the package structure, and I'm not very sure what to Google. I've been trying to find a common convention when it comes to how npm packages are imported.

I've recently been writing a small web server in Node, and I've been using HttpDispatcher to help take care of requests. The problem comes in when I attempt to make more than one HttpDispatcher 'object.' When I do, it doesn't actually create a new one, and instead continues to use the first one I create.

I'm fairly new to Javascript and Node in general, however I have run into issues in the past where creating anonymous functions (I think that's what they're called) within a loop does not always, if at all, do as intended. Thus, I'm really curious how packages that are meant to have multiple instances are generally used?

I fixed my problem by making the HttpDispatcher 'object' global (removing the var keyword in front. This will actually create a new object as expected. I'm worried that this is not proper, though.

So I'm asking you: What is the proper way to declare/initialize/export objects that are declared in an npm package? Should I submit a pull request or suggestion to the author of this package with my issues?

Much appreciated!

Upvotes: 1

Views: 399

Answers (1)

Delapouite
Delapouite

Reputation: 10157

You're right, you should contact the author of the HttpDispatcher module

At the end of the HttpDispatchermodule, instead of exporting an instance :

module.exports = new HttpDispatcher();

The author could export the constructor itself, and then you could make as many instances as you need in consumer modules :

module.exports = HttpDispatcher;

Upvotes: 2

Related Questions