What exactly does module.exports do in Node.js, and what would a simple example be?
What exactly does module.exports do in Node.js, and what would a simple example be?
module.exports
in Node.js is a special object that is used to export values from a module so that they can be used by other modules through the require()
function. Essentially, it defines what a module will expose or make available to other parts of your application or to other modules when they are included using require()
.
Here's a simple example to illustrate how module.exports
works:
// In a file named greet.js
function sayHello(name) {
return `Hello, ${name}!`;
}
// Export the function using module.exports
module.exports = sayHello;
In the example above, the sayHello
function is exported from the greet.js
file using module.exports
. This makes sayHello
available to be imported into other files.
Now, in another file, you can use the exported sayHello
function like this:
// In another file that requires the greet module
const greet = require('./greet');
// Use the imported function
console.log(greet('World')); // Outputs: Hello, World!
By requiring greet.js
, you get access to the sayHello
function because it was exp...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào