Creating a hello-world.js module

suggest change

Node 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:

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"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents