Sunday, 12 September 2021

Modules in Node.js

Node.js uses CommonJS module format. It uses require to include a module. It uses module.exports to expose a modules. The npm ecosystem also uses this format.

Use require to include a module. The below we include express module.


const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

const port = 2000
app.listen(port, () => {
  console.log(`listen to port 2000...`)
})

Use exports to let other codes to use this module. For example, AWS Lambda function can be written in Node.js

exports.myFunction = (event, context, callback) => {
        //do something
}

The below is a hello world module and how to use it

//in hello-world.js create a module
module.exports = name => console.log("hello to " + name)

//in main.js
var hw = require('./hello-world')
hw("kei")

//run it
node main.js //output: hello to kei
//another example
//in config.js
module.exports = {
  dbPort : 8080,
  dbHost : "etc",
  dbName : "nom",
}

//in main.js
var config = require("./config")
console.log("config:", config);
//more example
//in config
module.exports = {
  dbPort : 8080,
  dbHost : "etc",
  dbName : "nom",
  hello: (name)=> "hello to " + name
}

//in main
var leo = require("./config")

console.log(leo)

console.log(leo.hello("smith"))

//output node main.js
{
  dbPort: 8080,
  dbHost: 'etc',
  dbName: 'nom',
  hello: [Function: hello]
}
hello to smith

However, for ES6, it uses another format. It uses export and import to export and include a module. Here is post about default values in ES6 module

No comments:

Post a Comment