Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPiotr Andrzejewski
6,874 PointsHow to write modules
Hello !
I am during the node.js basic course on the Handling Errors in Node chapter. I am trying to improve the app by extracting all the printing methods into its own module. I would like someone to advise if my approach is correct... I have created a file named print.js with code inside:
```function print() { this.error = function() { } this.message = function() { }
module.exports = print;```
Then in profile.js file I am importing it with the lines below:
const modulePrint = require("./print");
const print = new modulePrint();
later in the code, I use those function by writing print.error or print.message.
Finally in the app.js file i have only 3 lines of code:
const profile = require('./profile.js');;
const users = process.argv.slice(2);
users.forEach(profile.get);
This is the first time I have been using modules that's why it makes me wonder if I am doing it in the correct way or is there some more efficient way to do it.
2 Answers
miikis
44,957 PointsHi Piotr,
You'll only want to abstract code into its own module when the situation presents itself. Don't force it. You say:
I am trying to improve the app by extracting all the printing methods into its own module.
Be careful of notions like this. They seem like plausible endeavors, but they rarely are. Unless you can specify exactly how the app will be "improved" by the abstraction, move on to something more constructive... like implementing new features or fixing critical bugs.
Abraham Juliot
47,353 PointsHi Piotr, I would avoid using the "this" keyword since it's reference changes based on the context of the function. You could assign "this" to a const named anything, or you can avoid "this" altogether and instead of this.error and this.message, you can return an object: return { error: function() { }, message: function() {} }. Here's some additional guides: