Reputation: 1258
I have been trying to understand, module.export how to pass a parameter with it. Now I have made a demo server for testing it.
File - index.js
var express = require('express');
var check = require('./file');
var app = express();
app.get('/',check.fun1("calling"),(req,res)=>{
res.send('here i am');
})
app.listen(3000,()=>{
console.log("Server is up");
})
With a middleware check,
module.exports = fun1 = name => {
return function(req, res, next) {
console.log(name + " from fun1");
next();
};
};
module.exports = fun2 = name2 => {
return function(req, res, next) {
console.log(name + " from fun1");
next();
};
};
Now this is not working, but when I change it in, its start to work
fun1 = name => {
return function(req, res, next) {
console.log(name + " from fun1");
next();
};
};
fun2 = name2 => {
return function(req, res, next) {
console.log(name + " from fun1");
next();
};
};
module.exports = {
fun1,
fun2
};
Now, this might look like a stupid question, that if it's working then why I am asking but, what change should I make, in index.js file so that my first type of module.export starts working. It's just all out of sheer curiosity
Thanks
Upvotes: 0
Views: 1040
Reputation: 114014
A lot of things in node.js are simply design patterns. Node.js introduced exactly zero extensions to javascript when it was originally published (and this includes its module system). Even today, node.js has zero syntax extensions. Node.js is just javascript with additional libraries and a special runtime environment (where all modules are evaluated inside an IIFE)
Having said that, module.exports
is not syntax. It is simply an ordinary variable in javascript. Specifically, the variable module
is an object and node's module system will check this module
variable to see if it has a property named exports
. If module
has an exports
property then its value is taken to be the exported module.
Since module
is just an ordinary variable it follows normal variable behaviour. If you reassign a variable its value will change. For example:
var x = 0;
console.log(x); // prints 0;
x = 100;
console.log(x); // prints 100, not 0 and 100
Therefore, the same is true for module.exports
:
module.exports = 'hello';
console.log(module.exports); // prints 'hello'
module.exports = 'world';
console.log(module.exports); // prints 'world', not 'hello world'
Upvotes: 1