Lesson 3. Creating a Node.js module

In this lesson, you kick off Node.js application development by creating a Node.js module (JavaScript file). Then you introduce npm to the development workflow and learn about some common npm commands and tools for setting up a new application.

This lesson covers

  • Creating a Node.js module
  • Constructing a Node.js application with npm
  • Installing a Node.js package with npm
Consider this

You want to build an application to help people share food recipes and learn from one another. Through this application, users can subscribe, join online courses to practice cooking with the application’s recipes, and connect with other users.

You plan to use Node.js to build this web application, and you want to start by verifying users’ ZIP codes to determine the locations and demographics of your audience. Will you need to build a tool for checking ZIP codes in addition to the application?

Luckily, you can use npm to install Node.js packages—libraries of code others have written that add specific features to your application. In fact, a package for verifying locations based on ZIP codes is available. You take a look at that package and how to install it in this lesson.

A Node.js application is made up of many JavaScript files. For your application to stay organized and efficient, these files need to have access to one another’s contents when necessary. Each JavaScript file or folder containing a code library is called a module.

Suppose that you’re working on a recipe application using the positive messages from unit 0. You can create a file called messages.js with the following code: let messages = [You are great!,You can accomplish anything!,Success is in your future!];.

Keeping these messages separate from the code you’ll write to display them makes your code more organized. To manage these messages in another file, you need to change the let variable definition to use the exports object, like so: exports.messages = [You are great!,You can accomplish anything!,Success is in your future!];. As with other JavaScript objects, you’re adding a messages property to the Node.js exports object, and this property can be shared among modules.

Note

The exports object is a property of the module object. module is both the name of the code files in Node.js and one of its global objects. exports is shorthand for module .exports.

The module is ready to be required (imported) by another JavaScript file. You can test this module by creating another file called printMessages.js, the purpose of which is to loop through the messages and log them to your console with the code shown in the next listing. First, require the local module by using the require object and the module’s filename (with or without the .js extension). Then refer to the module’s array by the variable set up in printMessages.js, as shown in the next listing.

Listing 3.1. Log messages to console in printMessages.js
const messageModule = require("./messages");               1
messageModule.messages.forEach(m  => console.log(m));      2

  • 1 Require the local messages.js module.
  • 2 Refer to the module’s array through messageModule.messages.

require is another Node.js global object used to locally introduce methods and objects from other modules. Node.js interprets require(./messages) to look for a module called messages.js within your project directory and allows code within printMessages.js to use any properties on the exports object in messages.js.

Using require

To load libraries of code and modules in Node.js, use require(). This require function, like exports, comes from module.require, which means that the function lives on the global module object.

Node.js uses CommonJS, a tool that helps JavaScript run outside a browser by helping define how modules are used. For module loading, CommonJS specifies the require function. For exporting modules, CommonJS provides the exports object for each module. Much of the syntax and structure you use in this book results from CommonJS module designs.

require is responsible for loading code into your module, and it does this by attaching the loaded module to your module’s exports object. As a result, if the code you’re importing needs to be reused in any way, it doesn’t need to be reloaded each time.

The Module class also performs some extra steps to cache and properly manage required libraries, but the important thing to remember here is that once a module is required, the same instance of that module is used throughout your application.

In the next section, you use npm, another tool for adding modules to your project.

Quick check 3.1

Q1:

What object is used to make functions or variables within one module available to others?

QC 3.1 answer

1:

exports is used to share module properties and functionality within an application. module.exports can also be used in its place.

 

3.1. Running npm commands

With your installation of Node.js, you also got npm, a package manager for Node.js. npm is responsible for managing the external packages (modules that others built and made available online) in your application.

Throughout application development, you use npm to install, remove, and modify these packages. Entering npm -l in your terminal brings up a list of npm commands with brief explanations.

You’ll want to know about the few npm commands listed in table 3.1.

Table 3.1. npm commands to know
npm command Description
npm init Initializes a Node.js application and creates a package.json file
npm install <package> Installs a Node.js package
npm publish Saves and uploads a package you build to the npm package community
npm start Runs your Node.js application (provided that the package.json file is set up to use this command)
npm stop Quits the running application
npm docs <package> Opens the likely documentation page (web page) for your specified package

When you use npm install <package>, appending --save to your command installs the package as a dependency for your application. Appending --global installs the package globally on your computer, to be used anywhere within terminal. These command extensions, called flags, have the shorthand forms -S and -g, respectively. npm uninstall <package> reverses the install action. In unit 2, you’ll use npm install express -S to install the Express.js framework for your project and npm install express-generator -g to install the Express.js generator for use as a command-line tool.

Note

By default, your package installations appear in your dependencies as production-ready packages, which means that these packages will be used when your application goes live online. To explicitly install packages for production, use the --save-prod flag. If the package is used only for development purposes, use the --save-dev flag.

Later, when you prepare your application for production, making it available for the world to use, you may distinguish packages by using the --production flag.

Modules, packages, and dependencies

Throughout your development with Node.js, you’ll hear the terms modules, packages, and dependencies thrown around a lot. Here’s what you need to know:

  • Modules are individual JavaScript files containing code that pertains to a single concept, functionality, or library.
  • Packages may contain multiple modules or a single module. They’re used to group files offering relevant tools.
  • Dependencies are Node.js modules used by an application or another module. If a package is considered to be an application dependency, it must be installed (at the version specified by the application) before the application is expected to run successfully.

If you’d like to incorporate some functionality in your application, you can likely find a package that performs this task at https://www.npmjs.com. To your recipe application, add the ability to find where your users are located based on their ZIP codes. If you have this information, you can determine whether users live close enough together to cook with one another.

To add this feature, you need to install the cities package (https://www.npmjs.com/package/cities), which converts text addresses to location coordinates. But you still need one more thing for this project before you can install the package successfully. In the next section, you properly initialize a Node.js project and create a package.json file that npm will use to install cities.

Quick check 3.2

Q1:

What flag do you use if you want to install a package globally on your computer?

QC 3.2 answer

1:

The --global or -g flag installs a package for use as a command-line tool globally on your computer. The package can be accessible to other projects, not exclusively to the one you’re working on.

 

3.2. Initializing a Node.js application

Every Node.js application or module contains a package.json file to define the properties of that project. This file lives at the root level of your project. Typically, this file is where you specify the version of your current release, the name of your application, and the main application file. This file is important for npm to save any packages to the node community online.

To get started, create a folder called recipe_connection, navigate to your project directory in terminal, and use the npm init command to initialize your application. You’ll be prompted to fill out the name of your project, the application’s version, a short description, the name of the file from which you’ll start the app (entry point), test files, Git repositories, your name (author), and a license code.

For now, be sure to enter your name, use main.js as the entry point, and press Enter to accept all the default options. When you confirm all these changes, you should see a new package.json file in your project directory. This file should resemble the contents of the next listing.

Listing 3.2. Result of package.json file in recipe_connection project in terminal
{
  "name": "recipe_connection",
  "version": "1.0.0",
  "description": "An app to share cooking recipes",
  "main": "main.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Jon Wexler",
  "license": "ISC"
}                           1

  • 1 Display contents of package.json, containing a name, version, description, starting file, custom scripts, author, and license.

Now your application has a starting point for saving and managing application configurations and packages. You should be able to install cities by navigating to your project folder in terminal and running the following command: npm install cities --save (figure 3.1).

Figure 3.1. Installing a package in terminal

After you run this command, your package.json gains a new dependencies section with a reference to your cities package installation and its version, as shown in the following listing.

Listing 3.3. Result of your package.json file after package installation in terminal
{
  "name": "recipe_connection",
  "version": "1.0.0",
  "description": "An app to share cooking recipes",
  "main": "main.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Jon Wexler",
  "license": "ISC",
  "dependencies": {           1
    "cities": "^2.0.0"
  }
}

  • 1 Display dependencies section of package.json.

Also, with this installation, your project folder gains a new folder called node_modules. Within this folder live the code contents of the cities package you installed (figure 3.2).

Figure 3.2. Node.js application structure with node_modules

Note

You also see a package-lock.json file created at the root level of your project directory. This file is automatically created and used by npm to keep track of your package installations and to better manage the state and history of your project’s dependencies. You shouldn’t alter the contents of this file.

The --save flag saves the cities package as a dependency for this project. Check your package.json file now to see how the package is listed under dependencies. Because your node_modules folder will grow, I recommend that you don’t include it when you share the project code online. Anyone who downloads the project, however, can enter npm install to automatically install all the project dependencies listed in this file.

Test this new package by adding the lines in listing 3.4 to main.js. Start by requiring the locally installed cities package, and make it available in this file. Then use the zip_lookup method from the cities package to find a city by that ZIP code. The result is stored in a variable called myCity.

Note

I’ll continue to use the var keyword for variable definitions where appropriate. Because myCity is a variable that could change value, I use var here. The cities variable represents a module, so I use const. I use the let variable when the scope of my code could specifically benefit from its use.

Listing 3.4. Implementing the cities package in main.js
const cities = require("cities");             1
var myCity = cities.zip_lookup("10016");      2
console.log(myCity);                          3

  • 1 Require the cities package.
  • 2 Assign the resulting city by using the zip_lookup method.
  • 3 Log the results to your console.

The resulting data from that ZIP code is printed to console as shown in the following listing. The zip_lookup method returns a JavaScript object with coordinates.

Listing 3.5. Sample result from running main.js in terminal
{
  zipcode: "10016",
  state_abbr: "NY",
  latitude: "40.746180",
  longitude: "-73.97759",
  city: "New York",
  state: "New York"
}                        1

  • 1 Display the results from the zip_lookup method.
Quick check 3.3

Q1:

What terminal command initializes a Node.js application with a package.json file?

QC 3.3 answer

1:

npm init initializes a Node.js app and prompts you to create a package.json file.

 

Summary

In this lesson, you learned about npm and how to use its array of tools to create a new Node.js application and install external packages. You built your own Node.js module and required it in your main application file. Last, you installed an external package and got it working in your sample app. The next step is integrating these tools into a web application. I discuss the first steps of building a web server in lesson 4.

Try this

Create a couple of new modules, and practice adding simple JavaScript objects and functions to the exports object.

You can add a function as shown in the following listing.

Listing 3.6. Exporting a function
exports.addNum = (x, y) => {      1
  return x + y;
};

  • 1 Export a function.

See what happens when you require modules from within another directory in your project folder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset