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:

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

middle

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

junior

What's the difference between process.cwd() vs __dirname ?

middle

When would you use cluster module in Node.js?

senior

What is the difference between the child_process spawn and execute functions in Node.js? When to
use each one?

Bình luận

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

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