最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should node.js modules export named functions or an object? - Stack Overflow

programmeradmin5浏览0评论

Which is the better pattern to use when creating modules in Node.js that have multiple functions that are called "statically" i.e. not using the new keyword. Is there an equivalent in ES6 I am missing?

Pattern 1.

// math.js
module.exports.add = (x, y) => {
    return x + y;
}

module.exports.multiply = (x, y) => {
    return x * y;
};

// app.js
const math = require('./math.js');
console.log(math.add(2, 3));

Pattern 2.

// math.js
module.exports = {
    add: (x, y) => {
        return x + y;
    },
    multiply: (x, y) => {
        return x * y;
    }
};

// app.js
const math = require('./math.js');
console.log(math.add(2, 3));

Which is the better pattern to use when creating modules in Node.js that have multiple functions that are called "statically" i.e. not using the new keyword. Is there an equivalent in ES6 I am missing?

Pattern 1.

// math.js
module.exports.add = (x, y) => {
    return x + y;
}

module.exports.multiply = (x, y) => {
    return x * y;
};

// app.js
const math = require('./math.js');
console.log(math.add(2, 3));

Pattern 2.

// math.js
module.exports = {
    add: (x, y) => {
        return x + y;
    },
    multiply: (x, y) => {
        return x * y;
    }
};

// app.js
const math = require('./math.js');
console.log(math.add(2, 3));
Share Improve this question asked Dec 3, 2016 at 9:40 JustinJustin 45.5k83 gold badges213 silver badges312 bronze badges 1
  • 1 Your two patterns are exactly the same for all intents and purposes. – user663031 Commented Dec 3, 2016 at 13:22
Add a ment  | 

2 Answers 2

Reset to default 5

By default module.exports is an empty object. So, there is really no difference in result between your two patterns.

Your first pattern is just adding methods one at a time to the default empty object.

Your second pattern is creating a new object, adding methods to it and then replacing the default module.exports object with your new object.

Which is the better pattern to use when creating modules in Node.js that have multiple functions that are called "statically" i.e. not using the new keyword.

The result is the same either way and it is merely a matter of a coding style preference for which way you like to write the code.

Is there an equivalent in ES6 I am missing?

ES6 doesn't really introduce anything new for this. You're just defining properties of an object.

I guess there is no "correct way" or "correct pattern" for that. In both cases you are telling mostly the same thing. You're just writing it a little bit different. Both will be transformed in an object and imported by some other module.

That being said, I like the second one. It gives me a sense of better "bundling".

I would, though, import as

import { add, multiply } from './math'
发布评论

评论列表(0)

  1. 暂无评论