Josh
Josh

Reputation: 7405

How to write an NPM module that uses multiple files?

I have a simple local command-line module that I want to use in 2 different ways (basically different defaults), but it uses the same core logic, so I want to extract that logic into a third entity and use that from the two entry points.

I have everything working with two bin command scripts, but each file has its own copy of the logic to run, and I am not sure how to pull this duplicated code out into a third file within the same module. I figure I could do it by creating an entire separate module and loading it with require(), but I would rather just keep it together since it's tightly coupled.

The structure is like this:

bin\
  cmdone.js
  cmdtwo.js
core.js
package.json

I would like to move the logic, which currently exists in both cmdone.js and cmdtwo.js, into core.js and reference it from the two files in bin. Is this possible?

Upvotes: 2

Views: 844

Answers (2)

Josh
Josh

Reputation: 7405

Well, after some more poking around, I discovered that this works:

const test = require('../core.js');

I suppose I misunderstood the distinction between Node modules and NPM packages. I was basically equating the two, but it seems that you can create and use modules entirely within packages, they don't have to be one-to-one.

Upvotes: 1

a1626
a1626

Reputation: 2964

If i understand your question correct, then what you need is require function of nodejs

Upvotes: 1

Related Questions