Require
// greet.js var greet = function() { } module.exports = greet; // app.js const greet = require('./greet');
1. Node "require" is a method inside modules.js core, this method then points to a prototype method called require as well
https://www.ud emy.com/understand-nodejs/learn/v4/t/lecture/3509218?start=0
2. This then points to a "load" prototype method that gets the contents of the file using fs.readFileSync
3. It takes the content of greet.js script and wraps it in a Immediately Invoked Function Expression (IIFE)
NativeModule.wrap = function(script) { return NativeModule.wrapper[0] + script + NativeModule.wrapper[1]; } NativeModule.wrapper = [ '(function (exports, require, module, __filename, __dirname) {', '\n});' ];
4. Then given to V8 Engine as apply method.
var args = [self.exports, require, self, filename, dirname]; // self.exports is the greet function. return compliledWrapper.apply(self.exports, args); // self.exports evokes the greet() function
Require a folder
1. simple create a folder ie. "greeting"
2. Add an index.js file
3. Require then export the files using object literal
// --- greeting/index.js const english = require('./english'); const spanish = require('./spanish'); module.exports = { english: english, spanish: spanish } // --- greeting/english.js const greet = function greet() { console.log('Hello'); } module.exports = greet; // --- greeting/spanish.js const greet = function greet() { console.log('Hola'); } module.exports = greet;
page revision: 6, last edited: 16 Jan 2018 10:42