Listen to Your Favourite Programming Podcasts and Books on Audible - Here is a Free Trial - Click Here - Offer Limited Time Only
How to Create Your Own Node.js Module

How to Create Your Own Node.js Module

Marty Jacobs · Jan 2, 2019 00:00 · 329 words · 2 minute read

Alt Text!

1. Download & Install Node.js

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

NOTE: Anywhere you see MyCoolModule - Replace it with your own module name.

2. Create a Node Project

Create an empty project

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 Module to NPM

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

Login using your credentials:

npm login

After logging in, you’re ready to publish!

npm publish

Alt Text!

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')

Create the test node project

npm init

Install your created module

npm install mycoolmodule

Execute the test script

node test.js

Alt Text!

You Are Done!

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 picking up a copy of Node.js 8 the Right Way: Practical, Server-Side JavaScript That Scales