Image of How to create your own Node.js module

ADVERTISEMENT

Table of Contents

Introduction

In this quick tutorial, you'll learn how to create your very own Node.js module.

Once you have everything configured and deployed, you may want to look into options for monitoring your application - which is an essential part of the application lifecycle.

1. Download & install Node.js

Download and Install Node.js by choosing your OS from the list here:

https://nodejs.org/en/download/

NOTE: Anywhere you see MyCoolModule in this tutorial, replace it with your desired module name.

2. Create a Node project

Create an empty project using the following commands:

mkdir MyCoolModule

Execute the following command:

cd MyCoolModule
npm init

Provide responses for the required fields (name and version), as well as the main field:

name: The name of your module. version: The initial module version. We recommend following semantic versioning guidelines and starting with 1.0.0. main: The name of the file that will be loaded when your module is required by another application. The default name is index.js.

Just press 'Enter' to the other questions...

3. Write your module

There should now be a package.json file inside your project directory. We need to write our code to upload it as a module.

Note: In this example, we are simply writing a function to print some text to the console.

Create a file and name it index.js in the project directory. Copy and paste the following code to index.js:

exports.printMsg = function() {
  console.log("Node.js is awesome!");
}

4. Publish the module to NPM (Node Package Manager)

If you don't have an npm account - Create one below:

https://www.npmjs.com/signup

Login using your credentials:

npm login

After logging in, you're ready to publish!

npm publish
Publish Node.js module

5. Test your module

Create another directory:

mkdir TestMyModule

Switch into the directory:

cd TestMyModule

Create your test script - I called mine test.js:

var mymodule = require('mycoolmodule')
mymodule.printMsg();

Create the test node project:

npm init

Install your created module:

npm install mycoolmodule

Execute the test script:

node test.js
Node.js module result

Conclusion

Thanks for reading! I hope you enjoyed the speed-run through setting up a node module using npm. Please don't forget to share this article. We'll be back again soon with more Node.js content!

Final Notes