In Node.js, how to import functions from another JavaScript file?

Posted on In QA

In Node.js, how to import functions from another JavaScript file like source common.sh in Bash?

In the .js file to be imported such as ‘common.js’, organize functions to be exported like

module.exports = {
  func1: function () {
    // func1 impl
  },
  func2: function () {
    // func2 impl
  }
};

In the other .js files, you can “include” the ‘common.js’ by

var common = require('./common');

In the following code, the functions can be used like

common.func1();

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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