Hi, I have controller code in back-end :
const getText = (req, res) => {
res.status(200).json({
message: "Get text",
});
};
const setText = (req, res) => {
res.status(201).json({
message: "Set text",
});
};
at the bottom of the file, I want to export them but I am confused either :
module.exports = { getText, setText };
or
module.exports = getText, setText;
Which one is correct or more proper ?
Thank you.
jenovs
February 27, 2022, 10:29am
2
First one. The second one won’t even work.
1 Like
lasjorg
February 27, 2022, 3:21pm
3
Well, it won’t work as expected. But it will sort of work, it will just only export the first variable. So you would only have access to getText
.
It is just a property with an object.
const module = {
exports: {},
};
module.exports = 'valueOne', 'valueTwo';
console.log(module.exports); // 'valueOne'
If you need multiple values you can either assign them to properties
module.exports.getText = getText;
module.exports.setText = setText;
Or you can wrap the values in a data structure that can contain multiple values like an object as your second example.
module.exports = { getText, setText };
You can also try logging out module
inside your code to see it.
console.log(module)
module.exports = getText, setText;
console.log(module)
1 Like
Just to expand, module.exports
is for you to define the default export of a module (equivalent to export default
when using native JS modules).
So module.exports = { getText, setText };
is saying “make the default export of this module an object which has two properties (getText
and (setText
)”
Second version uses this:
The comma operator (,) evaluates each of
its operands (from left to right) and returns the value of the last operand. This lets
you create a compound expression in which multiple expressions are evaluated, with the
compound expression's final...
So module.exports = getText, setText
is saying “make the default export of this module the function getText
, then evaluate the function setText
(which will do nothing)”
1 Like
Thank you very much, I got it !
system
Closed
September 1, 2022, 4:56pm
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.