2

app.js:

global.fs = require('fs');

require('./process.js').init();

process.js

// Do stuff with `fs`
fs.realpathSync(...); // etc.

Is it acceptable to save fs under global so that the code within process.js can access fs without having to re-require it?

Or is there some other way I should be doing this?

James
  • 109,676
  • 31
  • 162
  • 175

2 Answers2

2

I believe it is generally not acceptable for a library intended for general distribution to depend on using global variable(s) for anything. The issue is that unless the user knows exactly what globals are used by the library they might get overwritten (intentionally or inadvertently) and cause unexpected behavior of the application or library.

In your specific example, "process.js" should be fine to require the module again. Due to the caching behavior of modules in node.js the overhead of calling "require" again is trivial and it is guaranteed to get exactly the same object that you would have passed through the global (without the risk inherent to using global variables).

maerics
  • 151,642
  • 46
  • 269
  • 291
-1

This is similar question to node.js require inheritance? I think you can skip global and just do:

fs = require('fs'); // in app.js

fs will be attached to global automatically and will be visible in process.js. Some people prefer to use global for visibility.

Community
  • 1
  • 1
Michal Kuklis
  • 871
  • 11
  • 14
  • 1
    No it won't. `fs` writes to `module.fs` not `global.fs`. In node.js the `don't use var` makes it module global not program global. – Raynos Jun 22 '11 at 08:44