Search code examples
node.jsreferenceerror

call export function in Node.js


I am new in node.js

I did try this function ( foo.js )

module.exports.hello = function hello(name) {
 console.log("hello " + name);   
}

hello('jack');

but I have this error

node foo.js
ReferenceError: hello is not defined

Solution

  • Creating a function on module.exports doesn't make that function globally available, but it will make it available on the object returned when requiring your file from another file.

    So if we remove the call to hello from your foo.js file:

    module.exports.hello = function hello(name) {
     console.log("hello " + name);   
    }
    

    and create another file called bar.js in the same directory:

    var foo = require('./foo');
    foo.hello('jack');
    

    Then we get the desired output:

    tim [ ~/code/node-test ]$ node bar
    hello jack
    tim [ ~/code/node-test ]$ 
    

    EDIT: Alternatively, if you just want to define a function for use in that file, you can just define a regular function at the top level like so:

    function hello(name) {
        console.log("hello " + name);
    }
    
    module.exports.hello = hello;
    
    hello('jack');
    

    Notice that by adding it to module.exports we could still use the function from bar.js, but if you don't need this functionality, you can omit this line.