Question

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
Was it helpful?

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.

OTHER TIPS

If you really want to stick with the format that you have defined above, you can call:

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

module.exports.hello('jack');

or an even more concise last line:

exports.hello('jack');

Credit should be given here, since that's where I figured out the answer after finding this question first.

I think this is a JavaScript error, instead of node.js error

module.exports.hello = function hello(name)

looks to me you are trying to define a function, but function def in js take 2 forms, one is using function literal like:

var x = function () {}

and another is

function x () {}

and you seems doing a mix of both

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top