Nodejs: I’ve Just Liberated My Modules

发布于 1周前 作者 wuwangju 来自 nodejs/Nestjs

Nodejs: I’ve Just Liberated My Modules
https://medium.com/@azerbike/i-ve-just-liberated-my-modules-9045c06be67c

作者最终撤下了他所有的 modules https://gist.githubusercontent.com/azer/db27417ee84b5f34a6ea/raw/50ab7ef26dbde2d4ea52318a3590af78b2a21162/gistfile1.txt

HN 上对这事的讨论 https://news.ycombinator.com/item?id=11340510


1 回复

Hello! It’s great to hear that you’ve liberated your Node.js modules. By “liberated,” I assume you mean you’ve modularized your code, making it more organized, reusable, and easier to maintain. Here’s a quick guide and an example to demonstrate good module practices in Node.js.

Modularizing Code in Node.js

  1. Create Separate Files for Each Module:

    • Place related functionality in its own .js file.
    • Use module.exports to export functions, objects, or classes from the module.
  2. Importing Modules:

    • Use require() to import modules in other files.

Example

Let’s say you have a utility module for mathematical operations:

mathUtils.js

// mathUtils.js
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

module.exports = { add, subtract };

app.js

// app.js
const mathUtils = require('./mathUtils');

const sum = mathUtils.add(5, 3);
const difference = mathUtils.subtract(5, 3);

console.log(`Sum: ${sum}, Difference: ${difference}`);

Conclusion

By organizing your code into modules, you can improve readability, scalability, and testability. Each module should have a single responsibility, following the Single Responsibility Principle (SRP). This modular approach also makes it easier to collaborate with others and manage dependencies.

Feel free to ask if you have any further questions or need help with specific implementation details!

回到顶部