Often when you create a node. JS program, we need to divide the code into logical dependencies and organize it into multiple modules instead of putting the code in a single file. This is necessarily the same as in other languages, there are mechanisms like packages or modules that can be used. We look at how modules are created and used in node. js.
1. Single File module
--function(A, B) {return a + b;}; var function (A, b) { return A- b;}; --main.jsvar module = require (' module '); Console.log (Module.add (1, 2));
In the above code, we created a single module modules, which defines two functions add and sub, where add can be used externally (note that exports is used), and sub can only be used within a file. Main.js introduces module modules using require, and then you can use the Add function.
2. Catalogue Module
Now we define a operation directory and then create a index.js file under the directory. The content is the same as in the module.js above, and then place the operation directory in the Node_modules directory. You can use the Add function with require (' operation ') in Main.js. Note in the catalog
defines the module in the The file is set to Index.js file by default, if you want to use other files such as current.js as a module file, you should specify the main property in Package.json in the module directory as current.js, otherwise you will not be prompted to find the corresponding module .
node. JS Module