Node & Node Modules
Table of Contents:
Slides
Overview
In this lesson we'll learn the history of Node and the fundamentals of using Node Modules to build JavaScript scripts.
Key Terms
Node is a "JavaScript runtime environment" which is just a fancy way to say it is a program for running JavaScript.
A module is an exported chunk of code (typically a function or a set of functions) that can be used across our project.
In a Node project, a file exports a module by assigning a value to
module.exportsA file can export a module in two ways:
It can export one value/function (a single "default export")
It can export many values/functions (a group of "named exports")
A module can be imported with the
require(filename)function.Modules can be downloaded from the Node Package Manager (NPM) online registry
When a module is downloaded, it is called a dependency
package.jsonis a file with meta-data about a Node project including dependencies and configuration.JavaScript Object Notation (JSON) is a file format for representing data in an JavaScript-Object-like notation with key:value pairs.
Developer dependencies are dependencies used by the developer(s) who created the package but aren't needed by the users of the package. They are not added to the
node_modulesfolder of the user.
What is Node?
JavaScript started out as a language that could only be executed by a browser.
In 2009, Node was invented to allow programmers to run JavaScript on their own computers without a browser, opening the door for fullstack JavaScript development.
Node is a "JavaScript runtime environment" which is just a fancy way to say it is a program for running JavaScript.
To run a JavaScript program, we use the command
node <file_name>

If you use the
nodecommand on its own, you will open the Node Read Evaluate Print Loop (REPL) program.

Exporting and Importing Node Modules
Consider the simple JavaScript program below. It declares a few functions for calculating data about a circle with a given radius and then prints them out.
// functions for circle stuff
const LAZY_PI = 3.14;
const getArea = (radius) => {
return LAZY_PI * radius * radius;
}
const getDiameter = (radius) => {
return radius * 2;
}
const getCircumference = (radius) => {
return LAZY_PI * radius * 2;
}
// function for printing stuff. It is a "wrapper" for the console.log function
const print = (input) => {
console.log(input);
}
// The main function just runs all of the other functions
const main = () => {
const radius = 5;
const area = getArea(radius);
print(`the area of a circle with radius ${radius} is ${area}`);
const diameter = getDiameter(radius);
print(`the diameter of a circle with radius ${radius} is ${diameter}`);
const circumference = getCircumference(radius);
print(`the circumference of a circle with radius ${radius} is ${circumference}`);
}
main();Notice that the
mainfunction just uses the other functions.JavaScript projects are rarely built entirely in one file like this. Instead, code is separated into multiple files that share code with each other.
These shared pieces of code are called modules. A module is an exported chunk of code (typically a function or a set of functions) that can be used across our project.
For example, a file can create a function and then export it.
Meanwhile, another file can import that function and use it.
Modules help with organization and separation of concerns but require more files!
Exporting with module.exports (CommonJS)
module.exports (CommonJS)In a Node project, a file exports a module by assigning a value/function to
module.exports.
const print = (input) => {
console.log(input)
}
module.exports = print;When
module.exportsis assigned a single value/function, we call that a default export.You will also commonly see
module.exportsbe assigned to an object containing multiple values/functions. These are called named exports:
const LAZY_PI = 3.14;
const getArea = (radius) => {
return LAZY_PI * radius * radius;
}
const getDiameter = (radius) => {
return radius * 2;
}
const getCircumference = (radius) => {
return LAZY_PI * radius * 2;
}
module.exports = {
LAZY_PI,
getArea,
getDiameter,
getCircumference
};Importing with require() (CommonJS)
require() (CommonJS)To import a value/function exported from another file, use the
require(filepath)function and provide afilepathargument.
// The variable name here is up to you since only the value is exported, not the variable.
const print = require('./print.js');
// circleHelpers is what we'll call the object that is exported
const circleHelpers = require('./circle-helpers.js');
const main = () => {
const radius = 5;
// the getArea method is INSIDE of the circleHelpers object so we use dot notation
const area = circleHelpers.getArea(radius);
// print was the default export of print.js so we can just invoke it.
print(`the area of a circle with radius ${radius} is ${area}`);
//... the rest of the code ...
}
main();Destructuring
If the exported value is an object, we typically will destructure the object immediately upon importing it:
// With destructuring, we create a variable for each named export.
const { getArea, getDiameter, getCircumference } = require('./circle-helpers.js');
const main = () => {
const radius = 5;
// We can just invoke getArea now without digging through an object.
const area = getArea(radius);
print(`the area of a circle with radius ${radius} is ${area}`);
//... the rest of the code ...
}
main();Node Package Manager (NPM)
Modules can be downloaded from the Node Package Manager (NPM) online registry.
When you download a package, it is called a dependency.
Visit https://www.npmjs.com/ to explore available packages. Start by searching up the "prompt-sync" package.

Installing and Using Dependencies from NPM
To install any module from npmjs, use the
npm install(ornpm i) command in your Terminal:
npm i prompt-sync # installs the prompt-sync packageNow, you should see a
node_modules/folder with aprompt-sync/folder inside. Open up theprompt-sync/index.jsfile to see the module that is exported!To use the package in our own program, use
require()again, this time with just the name of the module.
// with modules in node_modules, we only need to provide the name:
const prompt = require('prompt-sync')();
// we don't need to provide the full relative path (although we can)
const prompt = require('./node_modules/prompt-sync')();package.json and node_modules
package.json and node_modulesEvery dependency of a project, and its version number, will be listed in the file
package.json(if the file doesn't exist, thenpm icommand will create it). The existence of this file turns our project into a package.JavaScript Object Notation (JSON) is a file format for representing data in an JavaScript-Object-like notation with key:value pairs.

The downloaded module will be placed in a folder called
node_modules/along with any sub-dependencies that the module itself may require.You can see the sub-dependencies of a module by opening its own
package.jsonfile. All modules listed under"dependencies"will also be installed innode_modules/.In
prompt-sync/package.json, we can see it hasstrip-ansias a dependency.In
strip-ansi/package.json, we can see it hasansi-regexas a dependency.

Developer Dependencies
In the
prompt-sync/package.jsonfile, you will notice thatprompt-sync-historyis listed under"devDependencies".Developer dependencies are dependencies used by the developer(s) who created the package but aren't needed by the users of the package. They are not added to the
node_modulesfolder of the user.Try installing the
nodemonmodule as a developer dependency using thenpm i -Dcommand:
npm i -D nodemonYou should see
nodemonadded to the"devDependencies"section ofpackage.json(version numbers may vary):
{
"dependencies": {
"prompt-sync": "^4.2.0"
},
"devDependencies": {
"nodemon": "^3.1.7"
}
}The
nodemonmodule installs a new commandnodemonthat can be used to run a JavaScript file in "hot reload" mode. This means that any time you save a file in the project, it will re-run the file.
# runs index.js once
node index.js
# re-runs index.js each time the file changes
nodemon index.jspackage.json Scripts and nodemon
package.json Scripts and nodemonYou can add a
"scripts"section to thepackage.jsonfile to make it easier to run commonly used Terminal commands.Two common script commands to add are
"start"which runsnode index.jsand"dev"which runsnodemon index.js
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"dependencies": {
"prompt-sync": "^4.2.0"
},
"devDependencies": {
"nodemon": "^3.1.7"
}
}To use these commands, we can type
npm run script_name. For example,npm run startornpm run dev
npm init -y
npm init -yWhen working on a new Node project, it is common to set up the
package.jsonfile prior to installing any dependencies.This can be done using the command
npm initwhich will ask you some questions to generate apackage.jsonfile.
{
"name": "project-name",
"version": "0.0.1",
"description": "Project Description",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "the repositories url"
},
"author": "your name",
"license": "N/A"
}You can also run
npm init -yto skip the questions and build apackage.jsonfile using default values.
Madlib Challenge
A program is considered hard-coded if the program code must be modified in order to produce a new result.
The prompt-sync function is really useful for creating programs that will produce new results depending on the user's input.
const prompt = require('prompt-sync')();
const name = prompt(`Hello there! What's your name? `);
console.log(`hi ${name}. My name is HAL`);In the 6-madlib-challenge/index.js file you will find the following hard-coded program:
const madlib = (name, verb, quantity, item, newItem, isHappy) => {
console.log(`There once was a man named ${name}.`);
console.log(`Every day he would ${verb} with his ${quantity} ${item}s`);
if (isHappy) {
console.log(`But then, he found a ${newItem} and everything changed!`);
} else {
console.log(`But then, a ${newItem} took over his life and he couldn't ${verb} again!`);
}
console.log("The end.")
}
const main = () => {
const name = 'Ben';
const verb = 'run';
const quantity = 50;
const item = 'dog';
const newItem = 'new car';
const isHappy = false;
madlib(name, verb, quantity, item, newItem, isHappy);
}Your goal is to do the following in the 6-madlib-challenge folder:
Download the
prompt-syncmodule usingnpm i prompt-syncImport and configure the
promptfunction inindex.jsReplace the hard-coded variables defined in the
mainfunction with values retrieved from the user via thepromptfunction.Re-organize the code such that the
madlibfunction is in its own file calledmadlib.jsthat exportsmadlibas the default export.
If you get stuck, you can view the solution below:
Last updated