Introduction to Node.js & npm
Workplace Context
Your team is starting a new backend project, and the tech lead has decided to use Node.js. As a developer, you are expected to understand the fundamentals of the Node.js environment, manage project dependencies effectively, and structure code in a modular way. This lesson will provide you with the foundational knowledge required to get started.
Learning Objectives
By the end of this lesson, you will be able to:
- Explain what Node.js is and how it enables server-side JavaScript.
- Initialize a new Node.js project using npm.
- Manage project dependencies with a
package.json
file. - Create and use modules to organize and share code.
What is Node.js?
Node.js is a JavaScript runtime environment that allows you to run JavaScript code on the server, outside of a web browser. Traditionally, JavaScript was only used for client-side scripting in browsers. Node.js changed that by providing the tools and environment needed to build scalable and high-performance backend applications, like web servers and APIs.
It is built on Chrome’s V8 JavaScript engine, the same engine that powers Google Chrome, which makes it very fast.
The Node.js Event Loop
One of the most important concepts in Node.js is the event loop. Node.js operates on a single-threaded, non-blocking I/O model. This means it can handle many connections simultaneously without getting stuck waiting for one operation to complete.
Imagine a restaurant with only one waiter. Instead of taking an order, going to the kitchen, waiting for the food to be cooked, and then serving it before taking the next order (blocking), the waiter takes an order, gives it to the kitchen, and immediately goes to the next table to take another order (non-blocking). When the food is ready, the kitchen notifies the waiter, who then serves it. This is the essence of the event loop, making Node.js very efficient for I/O-heavy applications like web servers.
Getting Started with npm
npm
stands for Node Package Manager. It is the default package manager for Node.js and is automatically installed when you install Node.js. It helps you do two main things:
- Install and manage third-party packages (libraries and tools) in your project.
- Run scripts to automate tasks like starting your server or running tests.
Installing Node.js and npm
If you have not already installed Node.js and npm, you can download them from nodejs.org .
Initializing a Project
Every Node.js project starts with a package.json
file. This file contains metadata about your project (like its name and version) and, most importantly, lists all of its dependencies.
To create a package.json
file, you run the npm init
command in your terminal.
npm init -y
The -y
flag tells npm
to use the default settings, creating the file automatically without asking you any questions. After running this, you’ll see a package.json
file in your directory that looks something like this:
{
"name": "your-project-name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Installing Packages
Let’s say our project needs the express
package, a popular framework for building web servers. You can install it using npm install
.
npm install express
After running this command, you’ll notice two things:
- A new folder called
node_modules
has been created. This is wherenpm
downloads and stores all the packages your project needs. You should never edit files in this folder directly. - Your
package.json
file has been updated with a newdependencies
section.
{
// ... other properties
"dependencies": {
"express": "^4.18.2"
}
}
This entry tells npm
that your project depends on version 4.18.2 (or a compatible newer version, indicated by the ^
) of express
. Now, anyone else who downloads your project can run npm install
, and npm
will automatically download the correct version of all the required packages based on the package.json
file.
Modules in Node.js
As your application grows, you’ll want to split your code into multiple files to keep it organized and maintainable. In Node.js, each file is treated as a separate module.
Node.js uses the CommonJS module system, which has two core features:
- The
require()
function, used to import a module. - The
module.exports
object, used to export functionality from a module so it can be used elsewhere.
Creating and Exporting a Module
Let’s create a file named my-module.js
that exports a function.
const greet = (name) => {
return `Hello, ${name}!`;
};
module.exports = greet;
In this file, we define a function greet
and then assign it to module.exports
. This makes the greet
function available to any other file that imports this module.
Importing and Using a Module
Now, let’s create our main application file, index.js
, and use the greet
function from my-module.js
.
Here, require('./my-module.js')
imports the greet
function that we exported. The ./
indicates that the module is a local file in the same directory. We can then use the function just like it was defined in the same file.
You can also export multiple functions or values by assigning an object to module.exports
.
While our examples include html and css files, Node.js is a server-side runtime environment and does not support the DOM or browser-specific APIs. These files are included in our examples only because we are running them in a browser.
Using ES Modules
Node.js also supports ES Modules, which are a newer module system.
To use ES Modules, you need to change the file extension to .mjs
. Then, use the export
keyword to export modules and the import
keyword to import modules.
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
import { add, subtract } from './math.js';
console.log('Sum:', add(5, 3));
console.log('Difference:', subtract(5, 3));
You will see many variations of this syntax, but the core idea is the same.
Activities
Activity 1: Initialize Your Project
- Create a new directory for your project.
- Navigate into that directory in your terminal.
- Run
npm init -y
to create apackage.json
file. - Install the
nodemon
package as a development dependency (npm install nodemon --save-dev
).nodemon
is a tool that automatically restarts your server when you make changes. - Inspect your
package.json
file to see the newdevDependencies
section.
Activity 2: Create and Use Modules
- In your project, create two files:
app.js
andlogger.js
. - In
logger.js
, create a function calledlogMessage
that takes amessage
string as an argument and prints it to the console with a timestamp (e.g.,[2023-10-27T10:00:00.000Z] Your message here
). Export this function.- Hint: You can get an ISO timestamp with
new Date().toISOString()
.
- Hint: You can get an ISO timestamp with
- In
app.js
, import thelogMessage
function fromlogger.js
. - Call the
logMessage
function with a welcome message. - Run your application from the terminal using
node app.js
.
Knowledge Check
What is the primary purpose of the package.json
file?
- Select an answer to view feedback.
How do you make a function or variable from one file available for use in another file in Node.js?
- Select an answer to view feedback.
You want to install a package that is only needed for development (e.g., a testing tool or a linter). Which command should you use?
- Select an answer to view feedback.
Summary
In this lesson, you were introduced to the core concepts of Node.js. You learned what Node.js is, how to manage projects with npm
and package.json
, and how to structure your code using the CommonJS module system with require
and module.exports
. These skills are the essential first steps for building any backend application in Node.js.