What is this Javascript “require”?

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

    You know how when you are running JavaScript in the browser, you have access to variables like "window" or Math? You do not have to declare these variables, they have been written for you to use whenever you want.

    Well, when you are running a file in the Node.js environment, there is a variable that you can use. It is called "module" It is an object. It has a property called "exports." And it works like this:

    In a file that we will name example.js, you write:

    example.js

    module.exports = "some code";
    

    Now, you want this string "some code" in another file.

    We will name the other file otherFile.js

    In this file, you write:

    otherFile.js

    let str = require('./example.js')
    

    That require() statement goes to the file that you put inside of it, finds whatever data is stored on the module.exports property. The let str = ... part of your code means that whatever that require statement returns is stored to the str variable.

    So, in this example, the end-result is that in otherFile.js you now have this:

    let string = "some code";

    • or -

    let str = ('./example.js').module.exports

    Note:

    the file-name that is written inside of the require statement: If it is a local file, it should be the file-path to example.js. Also, the .js extension is added by default, so I didn't have to write it.

    You do something similar when requiring node.js libraries, such as Express. In the express.js file, there is an object named 'module', with a property named 'exports'.

    So, it looks something like along these lines, under the hood (I am somewhat of a beginner so some of these details might not be exact, but it's to show the concept:

    express.js

    module.exports = function() {
        //It returns an object with all of the server methods
        return {
            listen: function(port){},
            get: function(route, function(req, res){}){}
         }
    }
    

    If you are requiring a module, it looks like this: const moduleName = require("module-name");

    If you are requiring a local file, it looks like this: const localFile = require("./path/to/local-file");

    (notice the ./ at the beginning of the file name)


    Also note that by default, the export is an object .. eg module.exports = {} So, you can write module.exports.myfunction = () => {} before assigning a value to the module.exports. But you can also replace the object by writing module.exports = "I am not an object anymore."

提交回复
热议问题