✒️
SEI 802
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Node Packages
  • NPM
  • First Node Package: Nodemon
  • Using a Third Party Module

Was this helpful?

  1. Node/Express
  2. Node

Node Package Manager (NPM)

PreviousNode ModulesNextExpress

Last updated 3 years ago

Was this helpful?

There are three types of Node modules:

  • 1 Core Modules (like fs)

  • 2 Local Modules (that you create)

  • 3 Third Party Modules ( dependencies )

Core modules are great for gaining quick access to commonly-needed functionality in your program, and local modules allow you the flexibility to build out whatever tools you might possibly need, but third party modules, which fall somewhere in between, are perhaps the most exciting modules of them all!

Node Packages

Because developers are awesome, there are hundreds of thousands of already-written modules out there, ready for use! Each of these modules are encapsulated in a Node Package and made available via Node Package Manger or NPM, for short. A node package is a folder that contains one or more modules, a package.json file, and any meta-info needed to make the modules work correctionly and play well with your node program.

NPM

NPM is the largest open-source software registry in the world. It includes a website, a registry of Node Packages, and a command line interface that allows us to easily incorporate packages into our programs.

Check out this

The NPM CLI makes incorporating a node package into your program fairly easy, but you can refer to if you ever get lost. It includes a whole series of videos that demonstrate the fundamentals of using NPM.

The NPM CLI installed automatically on your machine when you installed Node. Verify this now by checking the version in your terminal: npm -v

First Node Package: Nodemon

is a package that makes developing node apps easier. It restarts the application everytime you save changes to your code.

We will use Nodemon quite a bit, so instead of installing it on each node app we build, we will install it globally. This will make it accessible to all of our node apps.

In the command line, type the following code: npm i -g nodemon

Since we're installing it globally (that's where the -g flag comes in), it doesn't matter what directory we're in.

Let's see nodemon in action! Try running your my-first-node-app using nodemon. Simply cd into the directory, then run nodemon. Nodemon knows to run the file that corresponds to main: in your package.json.

Now open up my-first-node-app in vs-code. Add the following code to index.js:

let i = 0;

const myTimer = setInterval(count, 1000);

count = () => {
    console.log(i);
    i++;
}

Make sure to save the file and check out what's happening in your terminal!

Now change the count function to print i*2 instead of just i and save.

You can always restart nodemon by typing rs.

To quit nodemon (and any program running in the terminal), press CTRL+C.

Congratulations, you've just installed and used your first third party node module!

We installed nodemon globally, but most node packages will only be useful for specific projects. In this case, when you run npm i [package name] you want to make sure you're inside the directory of the project you want to use the package in, and leave off the -g flag.

Using a Third Party Module

Introducing Moment: A Date/Time Format Module

Moment is a date formatting module. Instead of the mess of text that comes out when you create a regular date with JavaScript using the date class, we can pretty-print the date in a human readable way.

console.log(new Date());
// Prints: Fri Apr 05 2019 09:58:38 GMT-0700 (Pacific Daylight Time)

Install Moment

  1. Go to your terminal

  2. Make sure you're in the top level of your my-first-node-app folder

  3. Type the command npm i moment

  4. When the command is finished, go back to your text editor

  5. Make sure there is a folder called node_modules in the top level of your my-first-node-app folder

Use Moment in a Node App

  • Open index.js in your text editor

  • Require the moment library at the top of index.js and assign it to a variable called moment

  • Let's use the moment module to print a date! Add the following code to your index.js file:

console.log(moment().format("MMM DD YYYY"))
  • What does this print? You should have seen whatever today's date was in the format: 3-letter month, numerical day plus ordinal, and 4-digit year. For example:

Apr 15th, 2020
  • Next challenge: Use moment to pretty-print your birthday. Use the fully spelled out month, day of the week, escaped text for words such as the and of, and 4-digit year. For example:

Wednesday the 11th of September in the year 1985
  • BONUS: Use moment's .fromNow() function to print just how many years ago that birthday was!

Solution

 const moment = require('moment') 
 // Prints today's date 
 console.log(moment().format("MMM Do YYYY")) 
 // Prints my birthday 
 console.log(moment('09-20-1885', 'MM DD YYYY').format("dddd [the] Do [of] MMMM [in the year] YYYY")) 
 // Prints how long ago my birthday was 
 console.log('Oh boy, that was', moment('09-11-1985', 'MM DD YYYY').fromNow(), 'years ago!')

.gitignore File

Before we get too much further, WAIT!

Take a look at the node_modules folder that got generated when you used the npm install command. How big is this folder? How many files are in it? What's going on?

In general, we keep track of the version of the module that we are using in a file called package.json. This means we can just redownload the modules based on the version number on any new computer we want to put our code on - be that a fellow developer's computer or a production server. A package.json file might look something like this:

{
  "name": "node-introl",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "moment": "^2.24.0"
  }
}

Notice there is a "dependencies" section which lists our 3rd party dependencies. Right now we just have one, but others we install will go here, along with their version numbers in alphabetical order.

So, because we can just re-install the appropriate packages, we actually don't need to have the node_modules folder to be tracked by git at all! In fact, the node_modules folder can get so huge and unweildy that it's greatly preferred that you DO NOT push them up to github nor track them with version control! In fact, this can also cause serious errors during deployment!

How can we avoid this?!

We can specify directions to git about which files it should ignore by creating a file called .gitignore. Yes, the . at the front is necessary!

A .gitignore file will contain a list of files and folders that git should NOT be tracking. Go ahead and make a .gitignore file now and put node_modules into it as the first line.

.gitignore

node_modules

Congrats - now when you add git tracking to this folder, it will not track the node_modules folder and will not push it to github!

PROTIP : Use the following command in terminal to create .gitignore and add node_modules/:

echo "node_modules/" >> .gitignore

Other common things to ignore for git are things like .env files which contain localized settings and possibly sensitive data like secret keys, salts, or API keys. Thus leading to this pro-tip:

Life Pro Tip: .gitignore should be one of the first files you create in a project! Create it before you do a single check-in. Always. Don't be the developer who oopsed and put an API key in public.

Take a look at . There are a lot of things you can do with this module!

NPM Intro Video
this playlist
Nodemon
Moment's Docs