Creating your own Node module

In this article we are going to talk a little bit about creating NPM modules and sharing them on NPM registry, but first let’s define what’s NPM.

NPM is a package manager for Node.js packages, or modules and the npm website hosts thousands of free packages to download and use freely. NPM program is installed on your computer when you install Node.js.

Npm opens up an entire world of JavaScript talent for you and your team. It’s the world’s largest software registry, with approximately 3 billion downloads per week. The registry contains over 600,000 packages (building blocks of code). Open-source developers from every continent use npm to share and borrow packages, and many organizations use npm to manage private development as well.

To create a new module, start by creating a package.json file.

Use npm init to create package.json. It will prompt you for values for fields. The two required fields are ‘name’ and ‘version’. You’ll also need to set a value for ‘main’. You can use the default, index.js. These steps are described in detail in npm docs.

Once your package.json file is created, you’ll want to create the file that will be loaded when your module is required within a node program. The default name for this file is index.js.

In that file, add a function as a property of the exports object. This will make the function available to other code.

exports.printMsg = function() {
  console.log("This is a message from the demo package");
}

You can test this by publishing your package to npm, making a new directory outside of your project, switch to the new directory (cd)
and then running Run npm install . Then create a test.js file which requires the package and calls the method.

Run node test.js. The message sent to the console.log should appear.

Leave a comment

Leave a Reply