Search code examples
node.jsmodulerequire

NodeJS required module not available in other modules


I'm a bit new to NodeJS. Maybe it's just the way it works but to be sure:

My 'index.js':

var fs = require('fs');
// do something with fs here
var app = require('./app.js');

The 'app.js'

fs.readFile('/somedir/somefile.txt', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data);
});

Then I get an error:

ReferenceError: fs is not defined

As I've read, the 'solution' to this is to 're-require' the fs-module in app.js. Now what I do understand is that the fs-module is cached (any module, but using the example) so Node will still be really quick. What I don't really get is: "If the fs-module is cached, so actually it's kinda available anyway, why do I still have to 're-require' the module?

I'll be honest; it's just to understand why.


Solution

  • Each file has to include references to modules

    index.js

    var fs    = require("fs"),
        other = require("./otherfile"); 
    
    // you can now use `fs`
    

    otherfile.js

    var fs = require("fs");
    
    // you can now use `fs` here
    

    One of the best parts about this is you're not locked into naming the variable a certain way in any given file. Every file is pretty much isolated from all the other files in your lib, and that's a very good thing.

    Also know that you can include just parts a module if you'd like

    var read = require("fs").readFile;
    
    read("myfile.txt", function(err, data) {
      if (error) {
        return throw error;
      }
      console.log(data);
    };
    

    Explanation:

    Node.js does not encourage the use of globals; and as such, you should not try to implement things that depend on global variables.

    When you call in the fs module again, it's not really "re-requiring" it so much as you're just declaring a variable that points to the cached module.


    Additional example:

    In this answer I go into detail about how to structure a simple app that avoids the use of globals.