Câu hỏi phỏng vấn Nodejs
Câu hỏi

What exactly does module.exports do in Node.js, and what would a simple example be?

Câu trả lời

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:

javascript Copy
// 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:

javascript Copy
// 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

middle

Gợi ý câu hỏi phỏng vấn

middle

How does concurrency work in Node.js?

middle

When should we use Node.js?

middle

What are express.json() and express.urlencoded() in Express.js?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào