What is the syntax to export a function from a module in Node.js
function foo() {}
function bar() {}
// To export above functions:
module.exports = foo;
module.exports = bar;
// And in the file you want to use these functions,
// import them like this:
const foo = require('./module/path');
const bar = require('./module/path');
require function returns exports of the require module.
module.exports is the returned object.
1)use module.exports to export single varibale e.g one class or one function
e.g module.exports= Calculator.
2)use exports to export multiple named variables
export.add = (a,b)=> a+b;
export.multiple=(a,b)=> a*b;
mycoolmodule/index.js
module.exports = "123";
routes/index.js
var mymodule = require('mycoolmodule')
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(mymodule);
});
/*will show 123 in the terminal*/
module.exports = router;
// First Export from other file
export default exampleFunction;
// for multiple exports use:
module.exports = { exampleFunction1, exampleFunction2 };
// Then we import in the file where we want to use our functions
import exampleFunction from "./otherFile.js";
// for multiple imports, we desctructure
import { exampleFunction1, exampleFunction2 } from "./otherFile.js"
// Check MDN for more info on JS exports.
// NOTE: if running on node, add "type": "module" to your package.json file
//
What do "module.exports" and "exports.methods" mean in NodeJS / Express
// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works