How to Create Your Own Node.js Module

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

Alt Text!


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 - Replace it with your own module name.

2. Create a Node Project

Create an empty project

mkdir MyCoolModule

module

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:

https://www.npmjs.com/signup

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')
mymodule.printMsg();

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!