| Start |
|---|
| Creating a hello-world.js module Node provides the hello-world.js If we don't want the entire export to be a single object, we can export functions and variables as properties of the
hello-venus.js hello-jupiter.js hello-mars.js Loading module with directory name We have a directory named index.js main.js |
| Loading and using a module A module can be "imported", or otherwise "required" by the Aside from modules that are shipped with the runtime, you can also require modules that you have installed from npm, such as express. If you had already installed express on your system via You can also include modules that you have written yourself as part of your application. In this case, to include a file named Note that you can omit the extension, and |
| Every module injected only once NodeJS executes the module only the first time you require it. Any further require functions will re-use the same Object, thus not executing the code in the module another time. Also Node caches the modules first time they are loaded using require. This reduces the number of file reads and helps to speed up the application.
index.js |
| Folder as a module Modules can be split across many .js files in the same folder. An example in a my_module folder: function_one.js function_two.js index.js A module like this one is used by referring to it by the folder name: Please note that if you required it by omitting Alternatively you can create in the same folder a This way you are not required to name the main module file "index". |
| Invalidating the module cache In development, you may find that using To get around this issue, you will have to You could then delete the cache entry: And then require the module again: Do note that this is not recommended in production because the |
| Building your own modules You can also reference an object to publicly export and continuously append methods to that object: To use any of these, just require the module as you normally would: |
| Module loading from node_modules Modules can be For example, to Modules should be placed inside a directory, along with a Modules can also be we will be able to Note that node will only match the module that is closest to the file in the filesystem hierarchy, starting from (the file's current directory/node_modules). Node matches directories this way up to the file system root. You can either install new modules from the npm registry or other npm registries, or make your own. RemarksWhile everything in Node.js is generally done asynchronously, Modules are cached after the first time they are loaded. Should you be editing a module in development, you will need to delete its entry in the module cache in order to use new changes. That being said, even if a module is cleared out of the module cache, the module itself is not garbage collected, so care should be taken for its use in production environments. |
Read Article
https://develop.horje.com/learn/1434/reference