What is this Javascript “require”?

前端 未结 7 981
心在旅途
心在旅途 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:18

    It's used to load modules. Let's use a simple example.

    In file circle_object.js:

    var Circle = function (radius) {
        this.radius = radius
    }
    Circle.PI = 3.14
    
    Circle.prototype = {
        area: function () {
            return Circle.PI * this.radius * this.radius;
        }
    }
    

    We can use this via require, like:

    node> require('circle_object')
    {}
    node> Circle
    { [Function] PI: 3.14 }
    node> var c = new Circle(3)
    { radius: 3 }
    node> c.area()
    

    The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node.js application, you can simply use the require() method.

    Example:

    var yourModule = require( "your_module_name" ); //.js file extension is optional
    

提交回复
热议问题