Explain Codes LogoExplain Codes Logo

In Node.js, how do I "include" functions from my other files?

javascript
module-exports
destructuring
best-practices
Anton ShumikhinbyAnton Shumikhin·Sep 15, 2024
TLDR

To include functions from other files in Node.js, first export them using module.exports and then import them with require.

Exporting in utils.js:

// Remember the old saying: "Sharing is caring!" So, share this function! module.exports = function myUtil() { /* ... */ };

Importing in app.js:

// "Package delivered!" - Postman Pat, probably const myUtil = require('./utils'); myUtil(); // Function ushered into action

Good programming practice encourages us to keep code organized into reusable modules which are both maintainable and adhere to Node.js best practices.

Constructing your exports

The way you build your exports matters! Good structure means cleaner and more intuitive code.

Group related functions under a single umbrella (object):

// utils.js // I've got my ducks in a row... and by ducks, I mean functions. module.exports = { help: function() { /* ... */ }, parse: function() { /* ... */ }, };

This approach provides a namespace that keeps global scope pollution in check. Think of it as sorting out the utensils in your kitchen drawer.

Gathering multiple imports

When you're importing several functions, use destructuring like a pro to avoid jumbled code.

// app.js // Knock, knock! It's Destructuring! const { help, parse } = require('./utils');

This way you have direct access to your much-needed functions without burdening them with prefixes. It's like having a VIP backstage pass at a music concert.

Private party or public event?

Only exposed functions with module.exports get an invite when you call require. The uninvited ones stay private at home.

// utils.js // "In-house party only, sorry!" function privateUtil() { /* ... */ } // "Everyone's invited!" module.exports = function publicUtil() { /* ... */ };

For enhanced security and code isolation, keep the ones you don't want to be accessible at home.

Ducking the dangers of dynamic requires

It might look cool to use eval() and dynamic require for dynamic file loading, but remember, with great power comes great responsibility. Stick to static require() like Spiderman sticks to walls.

Steering away from common missteps

Ensure you've got the right type of functions when importing. It saves you from unexpected runtime errors, and you can confirm if the functions are exported correctly.

// app.js // Time for a litmus test! Is it an acid or a base? ... Oops! I mean function or undefined? const myUtil = require('./utils'); if (typeof myUtil === 'function') { /* ... use myUtil ... */ }

Also, ensure the paths in require() are spot on. Remember that one wrong turn while using require paths can lead you into the belly of the beast—module resolution errors.

When a function goes missing...

When a function goes MIA (not exported), it's deemed undefined when imported. Good news? You can set up error handling to deal with this smoothly.

// app.js // Calling out to a non-existent function? Sounds like a Detective Poirot case! const myUtil = require('./utils').missingUtil;

Keeping up with best practices and maintainability

Treat your utility modules like you'd treat a library. This means documenting your work like a meticulous librarian and making sure your functions handle their own errors internally just like a responsible adult.

// utils.js /** * @description This function has more personality than my pet rock. * @param {Array} input - An input more necessary than oxygen. * @return {boolean} - My magic 8-ball's answer! */ module.exports = function effectiveUtil(input) { if (!inputIsValid(input)) { throw new Error('Invalid input'); } /* ... logic ... */ };

As a result, your core application logic won't have to babysit the error handling of your utility functions and you're in for a smoother journey in the long run.

Enforcing 'use strict'

One child policy. No, wait... it's 'use strict'!

Using 'use strict' helps enforce more predictable code execution and fends off those pesky accidental global variables. It's like using sunscreen - better safe than sorry!

// utils.js 'use strict'; // "I, function, hereby solemnly swear that I'm up to good code execution!" module.exports = function goodUtil() { /* ... */ };