Node js Modules

Node js Modules


Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server-side and create server-side applications with JavaScript. One of the core features of Node.js is its support for modules, which are reusable pieces of code that can be exported and imported between different files and applications.

In Node.js, a module is simply a JavaScript file that exports an object or function. To export an object or function, you can use the module.exports or exports object. For example, let's say you have a file called "math.js" that exports a simple addition function:

You can then import this function into another file using the required function. For example, in a file called "app.js", you can import the add function and use it like this:

You can also export multiple objects or functions from a single module. For example, you can export an object containing multiple functions like this:

You can import this module and use the add and subtract function like this:

Node.js also comes with a built-in module system that provides a set of core modules, such as http, fs, and path, which provide functionality for working with the file system, creating HTTP servers, and more. These modules can be imported and used in the same way as custom modules.

In summary, Node.js modules are reusable pieces of code that can be exported and imported between different files and applications. They are created by exporting an object or function from a JavaScript file and are imported using the require() function. Node.js also comes with a built-in module system that provides a set of core modules.