Kai
Kai

Reputation: 3643

NodeJS : what is require modules best practices?

currently I've created a NodeJS project following below structures:

   /(root)
   ----> controller
       ----> aController.js
   ----> model
   ----> module
       ----> aModule.js
   ----> util
       ----> util.js
   app.js

The problem is example, in controller/aController.js I use the module fs, so I do fs = require('fs') to include the fs module.

The problem is in module/aModule.js I also want to use the fs, if I do another fs=require('fs') is it correct with "Node.js way"?

Same issue with above, I want to require('util/util.js') in both Modules and Controllers also. What's the best practice in this case?

Upvotes: 1

Views: 1103

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113335

Just do var fs = require("fs") (or var myLib = require("path/to/my/lib")) so many times you need (in different files).

require has an internal cache (require.cache), so same memory will be used.

From documentation:

require.cache

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.


Example

Having the following files:

.
├── a.js
├── b.js
└── u.js

u.js

this.say = "Hello World!";

a.js

var u = require("./u");
u.say = "Hello Mars!"; // change `say` property value
require("./b");        // load b.js file

b.js

console.log(require("./u").say); // output `say` property

Output: "Hello Mars!". Why? Because u.js loaded from b.js is loaded from require.cache (where u.say is set to "Hello Mars!" by a.js).

To prevent loading from cache you can remove files from require.cache using delete require.cache[<absolute-path-to-file>]. Let's change b.js content as follows:

 delete require.cache[require.resolve("./u")];
 console.log(require("./u").say); // output `say` property

Output: "Hello World!" because the file wasn't loaded from cache but from disk.

Upvotes: 4

Related Questions