Create a new directory for your project:
mkdir node-modules-example
cd node-modules-example
Initialize a new Node.js project using npm:
npm init -y
This will create a package.json
file with default settings.
Create a new file named math.js
to define a module:
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = { add, subtract };
Create another file named app.js
where we will use the created module:
// app.js
const math = require('./math');
const a = 10;
const b = 5;
console.log(`Addition of ${a} and ${b} is: ${math.add(a, b)}`);
console.log(`Subtraction of ${a} and ${b} is: ${math.subtract(a, b)}`);
Execute the app.js
file with Node.js:
node app.js
You should see the following output:
Addition of 10 and 5 is: 15
Subtraction of 10 and 5 is: 5
You can create additional modules to explore more functionality. Here are a couple of examples:
String Manipulation Module (stringUtils.js
):
// stringUtils.js
const toUpperCase = (str) => str.toUpperCase();
const toLowerCase = (str) => str.toLowerCase();
module.exports = { toUpperCase, toLowerCase };
Date Formatting Module (dateUtils.js
):
// dateUtils.js
const formatDate = (date) => date.toISOString().split('T')[0];
module.exports = { formatDate };
We will use the lodash
library as an example. Install it by running:
npm install lodash
lodashExample.js
:// lodashExample.js
const _ = require('lodash');
const array = [1, 2, 3, 4, 5];
// Get the last element of the array
const lastElement = _.last(array);
console.log(`The last element of the array is: ${lastElement}`);
// Create a new array with doubled values
const doubledArray = _.map(array, (num) => num * 2);
console.log(`Doubled array: ${doubledArray}`);
In the terminal, execute the lodashExample.js
file with Node.js:
node lodashExample.js
You should see the following output:
The last element of the array is: 5
Doubled array: [2, 4, 6, 8, 10]