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.
Your ReferenceError: require is not defined likely has one of two causes: You tried using require in a browser environment. You are in a Node. js environment but your project has "type": "module" in its package.
Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice.
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Each file has to include references to modules
var fs = require("fs"),
other = require("./otherfile");
// you can now use `fs`
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.
Sometimes we can forget it, but it's fundamental to declare it:
var fs = require('fs');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With