What is this Javascript “require”?

前端 未结 7 879
心在旅途
心在旅途 2020-11-22 03:46

I\'m trying to get Javascript to read/write to a PostgreSQL database. I found this project on github. I was able to get the following sample code to run in node.

<         


        
7条回答
  •  悲&欢浪女
    2020-11-22 04:24

    Two flavours of module.exports / require:

    (see here)

    Flavour 1
    export file (misc.js):

    var x = 5;
    var addX = function(value) {
      return value + x;
    };
    module.exports.x = x;
    module.exports.addX = addX;
    

    other file:

    var misc = require('./misc');
    console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));
    

    Flavour 2
    export file (user.js):

    var User = function(name, email) {
      this.name = name;
      this.email = email;
    };
    module.exports = User;
    

    other file:

    var user = require('./user');
    var u = new user();
    

提交回复
热议问题