What are the differences between : "module.exports = { foo, bar };" and "module.exports = foo, bar;"?

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.

First one. The second one won’t even work.

1 Like

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:

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 !

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.