A few examples of exports and require in Node.js

February 10, 2020 Goodman Loading... Post a comment

A few easy-to-understand examples below will help you understand “exports” and “require” in Node.js better.

Example 1

Exports (file your-file.js):

const firstMethod = () => {
    // do something
}

const secondMethod = () => {
    // do something
}

const text = 'Some text';

module.exports.first = firstMethod;
module.exports.second = secondMethod;
module.exports.text = text; 

// All the names are depend on your own

Require (file index.js)

const { first, second, text } = require("./your-file");

// Execution
first();
second();

console.log(text);

Examples 2

Export (call it your-file.js or whatever you like):


const firstMethod = () => {
    // do something
}

const secondMethod = () => {
    // do something
}

const text = 'Some text';

module.exports = {
    first: firstMethod,
    second: secondMethod,
    text: text
}

Require:

const x = require("./your-file");

// Execution
x.first();
x.second();

console.log(x.text);
avatar

Related Articles