Declare variables
In this section, we'll define and initialize the variables for a user's first name and last name. We'll then export these variables from the module so they can be used in other parts of our application.
Here is how we structure our names.js file:
and here is the names files
This code snippet demonstrates how to declare constants in JavaScript, which will hold the values of the user's first and last names. The module.exports statement makes these variables available for import in other JavaScript files, which is crucial for modular development where different parts of an application are kept in separate files.
Import Variables
Next, we'll use these variables in another file by importing them. This illustrates the modular nature of Node.js, allowing you to keep different parts of your application's logic separate and organized.
Here's how you can import and use the exported variables from names.js in app.js:
This example shows how to require the module we previously exported. By requiring ./names.js, we import the object containing firstName and lastName. The console.log statement then prints this object to the console.
when you run
, you will see output like this:And, that's how you can import and export variables in Node.