DEV Community

SavvyShivam
SavvyShivam

Posted on • Originally published at savvyshivam.hashnode.dev on

11. Import-Export Patterns in NodeJs

Node.js has become a popular choice for building server-side applications and JavaScript libraries. One of its key features is the ability to use the CommonJS module system, which allows you to organize your code into reusable and maintainable modules. In this article, we will explore import-export patterns in Node.js, providing a comprehensive guide with examples.

Understanding the CommonJS Module System

Before we dive into import-export patterns, let's understand how the CommonJS module system works in Node.js.

Exporting Modules

In Node.js, you can export values, functions, or objects from a module using the module.exports or exports object. Here's an example:

// myModule.js
const myFunction = () => {
  console.log("Hello, world!");
};

module.exports = myFunction;

Enter fullscreen mode Exit fullscreen mode

Importing Modules

To import modules in Node.js, you can use the require function. Here's how you can import the myModule.js module:

// app.js
const myFunction = require('./myModule');
myFunction(); // Outputs: Hello, world!

Enter fullscreen mode Exit fullscreen mode

Import-Export Patterns

Now that you have a basic understanding of how modules work in Node.js, let's explore some common import-export patterns.

1. Exporting Multiple Values

You can export multiple values from a module by attaching them to the exports object. Here's an example:

// math.js
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;

Enter fullscreen mode Exit fullscreen mode

To import and use these values in another module:

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

console.log(math.add(5, 3)); // Outputs: 8
console.log(math.subtract(5, 3)); // Outputs: 2

Enter fullscreen mode Exit fullscreen mode

2. Default Exports

Node.js also supports default exports. You can export a single value as the default export, making it the primary value when the module is imported. Here's an example:

// config.js
const port = 3000;
const databaseURL = 'mongodb://localhost/mydb';

module.exports = { port, databaseURL };

Enter fullscreen mode Exit fullscreen mode

To import the default export:

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

console.log(config.port); // Outputs: 3000
console.log(config.databaseURL); // Outputs: mongodb://localhost/mydb

Enter fullscreen mode Exit fullscreen mode

3. Importing Node.js Core Modules

Node.js provides a set of core modules that can be imported without specifying a path. These modules are accessible anywhere in your application. For example:

const fs = require('fs'); // Import the File System module
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Enter fullscreen mode Exit fullscreen mode

4. Importing Third-Party Modules

To use third-party modules, you need to install them using a package manager like npm or yarn. Once installed, you can import and use them in your project. For instance, to use the popular axios library for making HTTP requests:

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Enter fullscreen mode Exit fullscreen mode

5. ES6 Import-Export (Experimental)

Node.js has started to support ES6 module syntax for import and export statements. To use ES6 modules, you need to add "type": "module" to your package.json file and use the .mjs file extension. Here's an example:

// math.mjs
export function add(a, b) {
  return a + b;
}

// app.mjs
import { add } from './math.mjs';

console.log(add(5, 3)); // Outputs: 8

Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding import-export patterns is crucial for building modular and maintainable Node.js applications. Whether you're exporting single values, multiple values, or using default exports, Node.js provides flexible options to structure your code effectively. Additionally, the adoption of ES6 module syntax brings modern JavaScript practices to the Node.js ecosystem, offering even more versatility in how you organize and reuse your code.

Top comments (1)

Collapse
 
nyangweso profile image
Rodgers Nyangweso

awesome