Categories
JavaScript Answers

How to include functions from my other files with Node.js?

Spread the love

Sometimes, we want to include functions from my other files with Node.js

In this article, we’ll look at how to include functions from my other files with Node.js.

How to include functions from my other files with Node.js?

To include functions from my other files with Node.js, we can create our own module with module.exports.

For instance, we write

tools.js

module.exports = {
  foo() {
    // ...
  },
  bar() {
    // ...
  }
}

to assign module.exports to an object with the foo and bar functions in tools.js

Then we write

app.js

const tools = require('./tools');
tools.foo()
tools.bar()

to include the module in app.js by calling require with the path to tools.js and assign the module object to tools.

And then we can call the foo and bar functions from the module that we required.

Conclusion

To include functions from my other files with Node.js, we can create our own module with module.exports.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *