Image of How to create your own Node.js module

ADVERTISEMENT

Introduction

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

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!

If you are interested in learning more Node.js, we recommend subscribing to the Getting started with Node.js video series.

Getting started with Node.js provides a brief introduction to the Node.js framework. You will learn the basics of the Express.js framework, handling JSON objects, and protecting against common web security attacks.

If you're interested in what it entails to be a professional Node.js developer, check out this informative guide. It is useful for learning more about being a developer and how to hire one.