Gavin Gavin - 2 years ago 238
Javascript Question

Node.js package.json main parameter

I have done quite some search already. However, still having doubts about the main parameter in package.json of Node.js.

  1. How would filling in this field helps? Asking in another way, can I start the module in a different style if this field presents?

  2. Can I have more than one scripts being filled into the main parameter? If yes, would they being started as two threads? If no, how can I start two scripts in a module and having them run in parallel?

I know that the second question is quite weird. It is because I have hosted a Node.js application on OpenShift but the application consists of two main components. One being a REST API and one being a notification delivering service.

I afraid that the notification delivering process would block the REST API if they were implemented as a single thread. However, they have to connect to the same MongoDB cartridge. Moreover, I would like to save one gear if both the components could be serving in the same gear if possible.

Any suggestions are welcome.

Answer Source

From the npm documentation:

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.

This should be a module ID relative to the root of your package folder.

For most modules, it makes the most sense to have a main script and often not much else.

To put it short:

  1. You only need a main parameter in your package.json if the entry point to your package differs from index.js in its root folder. For example, people often put the entry point to lib/index.js or lib/<packagename>.js, in this case the corresponding script must be described as main in package.json.
  2. You can't have two scripts as main, simply because the entry point require('yourpackagename') must be defined unambiguously.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download