Section 3: Node.js Module System (Notes App)

9. Importing Node.js Core Modules

Some of the functionality in the Node.js API is provided by built-in global objects (like console). Other functionality is provided by modules that must be loaded using the require() function. For example, to load the file system module, as specified in the documentation, we use the following statement.

const fs = require('fs')

Here, require() loads the fs module and returns a reference to an object which we store in the variable fs. This object gives us access to the file system functionality available in Node.js as specified by the API documentation.

With it we can do things such as write to a file. For example the code below creates a file named notes.txt and writes to that file the string “created by node.js”.

fs.writeFileSync('notes.txt', 'created by node.js')

Test this by adding these lines of code to a file named write_file.js. Then run it with Node.js.

Challenge

Append the current Date to notes.txt using fs.appendFileSync().

const fs = require('fs')
fs.appendFileSync('notes.txt', '\n' + new Date().toString())

Part 10. Importing Your Own Files (a.k.a. modules)

The benefits to separating an app’s code into multiple JavaScript files include:

  • debugging: it is easy to locate and fix bugs when they are in smaller files.
  • testing: once the code in a file has been tested we can rely on its correctness.
  • reusability: the functionality contained in one file and be reused without causing code bloat.

We can consider the code in a file as a module. As we’ve seen in Part 9, JavaScript provides us with a mechanism to run the code in one file from another file using the require() method.

Passing Data From One Module to Another

A variable’s scope is restricted to the module in which it is declared. In order to exports data from a module and into another, as the fs module does, we set the module.exports field equal to the data we wish to export. For example, suppose we have a variable named name in a module named utils.js that we want accessible in other JavaScript files. Then in utils.js, we use the following code.

const name = 'Ian'
module.exports = name

To use the value(s) exported in another JavaScript file, say import_module.js, we use require() as shown below.

const firstName = require('./utils.js')
console.log(firstName)                   //prints Ian

Note the relative path to utils.js used by require(). Also note that the value exported by utils.js can be stored (in import_module.js) in a variable with any arbitrary name.

We can also export functions. In the example, below we modify utils.js to export a reference to an anonymous function expressed using a lambda expression.

const sum = (a,b) => a + b
module.exports = sum

We can import sum() using require() and then call the method as shown below. Note that utils.js exports a function named sum, yet we when we import the function with require we change the name to add.

constant add = require('./utils.js')
console.log(add(4,-2))                 //prints 2

Part 11. Importing npm Modules

When we installed Node.js the program npm was installed as well. The npm program can be used to install into a project’s code base modules from the npm website. Once a module is installed in a project’s code base we can load the module using require().

Before we can use npm in a particular project, we must initialize npm in the project (shown below). This creates a single JSON configuration file (packages.json) in the current working directory to keep track of the dependencies from the npm website that we are using.

$ npm init

Once npm is initialized in a project, we can install the npm packages that we need. The following command show how to install a particular version (13.0.0) of the module named validator.

$ npm install validator@13.0.0

When we install a npm module for the first time, a directory named node_modules is created in the project’s root directory and the module’s code is copied from the npm server to this directory. Note that you should never modify the node_modules directory directory.

We load an npm module in the same manner as loading a Node.js module using require(). Below we load the validator module and then call it’s isEmail() method.

const validator = require('validator')
...
console.log(validator.isEmail('joe@n0code.net')

If you encounter a Node.js project that is missing the node_modules directory but has npm dependencies listed in the packages-lock.json file, then you can install the dependencies by running the following command from the project’s root directory.

$ npm install

Part 12. Printing in Color

Do the challenge using the chalk npm package.

Part 13. Global npm Modules and nodemon

When we install a npm module using npm install ... on the command line, the module is installed locally in the node_modules directory. These modules are accessible in our app’s code.

We can also install a npm package globally. When we do, we can run the application in the package from the command line.

The nodemon package allows the user to automatically rerun an application when the code in the application changes.

We can install a package (e.g. nodemon) globally using the -g flag as shown below.

$ npm install nodemon@2.0.4 -g

To run an application with nodemon, we use nodemon instead of node on the command line. For example, to run an application named app.js with nodemon we would start the application with the following command.

$ nodemon app.js

Now when we change the source code and save the changes, nodemon automatically restarts the program.

© 2020 – 2024, Eric McGregor. All rights reserved. Unauthorized use, distribution and/or duplication of this material without express and written permission from the author is strictly prohibited.

Leave a Reply