Is it possible to export the whole Node.JS module without wrapping into a function/class?

496 views Asked by At

Is it possible to export the whole Node.JS module and have the following features:

  1. Import this module from another module
  2. Get all methods and attributes set into this module
  3. I do not want to wrap any part of this code from my module into a function/class?

For example, I want to create a REST.js module which has the following attributes and methods:

let a = 10
let b = 20
const funcA = (x) => {
//functionA code
}
const funcB = (x, y) => {
//functionB code
}

This module needs to be imported into app.js using some syntax which enables me to use the following API (or similar) to get attributes and use methods from REST.js:

const REST = require('REST')

//get attributes
console.log(REST.a)
console.log(REST.b)

//use methods

let resA = REST.funcA(10)
let resB = REST.funcB(10, 20)

All in all, I want to know if there is a similar to Python syntax for using modules.

1

There are 1 answers

2
Cuong Vu On BEST ANSWER

Yes, but in NodeJS, you must explicitly export the variables/functions like this:

let a = 10
let b = 20
const funcA = (x) => {
//functionA code
}
const funcB = (x, y) => {
//functionB code
}

module.exports = {
  a,
  b,
  funcA,
  funcB
}