Creating a hello-world.js module
suggest changeNode provides the module.exports interface to expose functions and variables to other files. The simplest way is to export a single function or value, as in the first example.
module.exports = function(subject) {
console.log('Hello ' + subject);
};
If the module should export more than one value, put functions and variables on module.exports. The next three files do that in slightly different ways:
hello-venus.js: the function is declared, then assigned onmodule.exportshello-jupiter.js: the functions are written directly as properties ofmodule.exportshello-mars.js: the function is assigned onexports, which starts as a reference tomodule.exports
function hello(subject) {
console.log('Venus says Hello ' + subject);
}
module.exports = {
hello: hello
};
module.exports = {
hello: function(subject) {
console.log('Jupiter says hello ' + subject);
},
bye: function(subject) {
console.log('Jupiter says goodbye ' + subject);
}
};
exports.hello = function(subject) {
console.log('Mars says Hello ' + subject);
};
Loading module with directory name
We have a directory named hello which includes the following files:
// hello/index.js
module.exports = function(){
console.log('Hej');
};
// hello/main.js
// We can include the other files we've defined by using the `require()` method
var hw = require('./hello-world.js'),
hm = require('./hello-mars.js'),
hv = require('./hello-venus.js'),
hj = require('./hello-jupiter.js'),
hu = require('./index.js');
// Because we assigned our function to the entire `module.exports` object, we
// can use it directly
hw('World!'); // outputs "Hello World!"
// In this case, we assigned our function to the `hello` property of exports, so we must
// use that here too
hm.hello('Solar System!'); // outputs "Mars says Hello Solar System!"
// The result of assigning module.exports at once is the same as in hello-world.js
hv.hello('Milky Way!'); // outputs "Venus says Hello Milky Way!"
hj.hello('Universe!'); // outputs "Jupiter says hello Universe!"
hj.bye('Universe!'); // outputs "Jupiter says goodbye Universe!"
hu(); // logs "Hej"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents