Node.js -2 | Modules: Custom Module and Sample Usage of Markdown Module

In this post, I’ll share some code about how to use modules in Node.js. I will use a custom module (user-defined) and a public module (Markdown module). The code samples are form’s Node.js lessons.


Defining a local module (A module that returns Fibonacci numbers)

1- In the root of Node.js application, navigate to node_modules folder and then create a dir for your module:

> cd node_modules
> mkdir data_module

2- Create module file:

> nano fibonacci.js

And edit its content like this: = [1,1,2,3,4,8,13,21];

Save and exit the editor.

3- In app root folder, create the main file:

> cd ..
> nano script.js

And edit like this:

// './' prefix tells that the module is local, not global
var sequence = require("./fibonacci");

Note: “Local modules are useful for when you want to separate your data from your code.”


Markdown module simple usage

First, create a Node.js app with Markdown module dependency enabled and install these dependencies as I talked about here.

In your script.js file:

var parser = require("node-markdown");
var html = parser.Markdown("This is a **markdown** text.");