How to require / export module(s) in node.js with sample codes

How to export / require custom module(s) in node.js

This article explain the way and sample codes.

Export/Require just one module

How to require only one module.

Sample code for exported module : fizz.js

module.exports = function(num){
  return num%3===0?"Fizz":""
}

Require the above module : app.js

/// Require fizz module
const fizz = require('./fizz.js')

console.log(fizz(3)) 
  /// => 'Fizz'

If you have only one module to export, assign a constant, function or class to module.exports.

Export/Require multiple modules

How to export and require multiple modules.

Sample code of exported modules : fizzzbuzz.js

exports.fizz = function(num){
  return num%3===0?"Fizz":""
}
exports.buzz = function(num){
  return num%5===0?"Buzz":""
}

Require the above modules : app.js

/// Require modules
const fizzbuzz = require('./fizzbuzz.js');
const fizz = fizzbuzz.fizz;
const buzz = fizzbuzz.buzz;
/// OR
/// const {fizz, buzz} = require('./fizzbuzz.js')

/// Output fizzbuzz from 0 to 99
for(let i=1; i<=100; i++){
  let rst=""
  rst += fizz(i)
  rst += buzz(i)
  if(rst===""){ rst=i.toString() }
  console.log(i, rst)
}

Output of above code :

1 1
2 2
3 Fizz
4 4
5 Buzz
6 Fizz
7 7
8 8
9 Fizz
10 Buzz
11 11
12 Fizz
13 13
14 14
15 FizzBuzz
16 16
17 17
18 Fizz
19 19
20 Buzz
21 Fizz

 

Leave a Reply