Stage 3: Backend Essentials

Node.js · Lesson 03

npm and Packages

package.json, installing dependencies, scripts and faster development with nodemon.

Node.js2 min readFree lesson

Almost no Node project is written from scratch. npm is the registry and the command-line tool that installs the work other people have published.

Learning objectives

  • Read and edit package.json.
  • Install, remove and update dependencies.
  • Tell dependencies and devDependencies apart.
  • Run project scripts and one-off binaries with npx.
  • Keep generated folders out of Git.

1. package.json

npm init -y creates it:

{
  "name": "date-dashboard",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "dependencies": {
    "dayjs": "^1.11.10"
  },
  "devDependencies": {
    "nodemon": "^3.0.2"
  }
}
  • name and version identify the package (lowercase, no spaces).
  • "private": true prevents accidentally publishing it.
  • "type": "module" switches .js files to ES modules.
  • scripts are shortcuts run with npm run <name>.

2. Installing packages

npm install dayjs              # runtime dependency
npm install --save-dev nodemon # development only
npm install                    # install everything from package.json
npm uninstall dayjs
npm outdated
npm update

dependencies are needed when the app runs in production. devDependencies are tools used while building — test runners, linters, nodemon. A production install (npm ci --omit=dev) skips them, keeping images small.

package-lock.json records the exact resolved versions of the whole tree. Commit it: it is what makes installs reproducible.

3. npx

npx runs a package binary without installing it globally:

npx create-next-app@latest my-app
npx prettier --write .

Global installs (npm i -g) are best avoided — projects then depend on whatever version happens to be on the machine.

4. nodemon

Restarting the server by hand after every edit gets old. nodemon watches the folder:

npm install --save-dev nodemon

With the script above, npm run dev restarts on save. In newer Node versions, node --watch server.js does the same without a dependency.

5. Using a package

const dayjs = require("dayjs");

const now = dayjs();
console.log(now.format("YYYY-MM-DD HH:mm:ss"));
console.log(now.add(100, "day").format("YYYY-MM-DD"));

const birthday = dayjs("1995-03-20");
console.log(now.diff(birthday, "year"), "years old");

Read the package README for its API; most libraries follow the same install → require → call shape.

6. .gitignore

Never commit node_modules or secrets:

node_modules/
.env
dist/
.DS_Store
*.log

Anyone who clones the project runs npm install and gets the same tree from package-lock.json.

Common mistakes

  • Committing node_modules — thousands of files and platform-specific binaries.
  • Installing a build tool as a runtime dependency.
  • Deleting package-lock.json to "fix" an install problem; it is the only record of what actually worked.
  • Forgetting to add .env to .gitignore before the first commit.

Practice

Build the date dashboard in the assignment. It is a real npm project: dependencies, scripts, a dev tool and a small CLI.

Example files

Complete, runnable files used in this lesson. Copy them into your project and experiment.

server.jsJavaScript
// ===================================================
// 강의 03 예제 — npm 패키지 활용
// 실행: npm run dev (nodemon 사용)
//       node server.js (직접 실행)
//
// 사전 준비:
//   npm init -y
//   npm install dayjs
//   npm install --save-dev nodemon
//   package.json scripts에 "dev": "nodemon server.js" 추가
// ===================================================

// dayjs 패키지 불러오기 (npm install dayjs 필요)
const dayjs = require('dayjs');

// 한국어 로케일 설정 (선택 사항)
// require('dayjs/locale/ko');
// dayjs.locale('ko');

console.log('=== dayjs 날짜/시간 라이브러리 예제 ===\n');

// ① 현재 날짜/시간
const now = dayjs();
console.log('현재 날짜:', now.format('YYYY-MM-DD'));
console.log('현재 시간:', now.format('HH:mm:ss'));
console.log('현재 날짜+시간:', now.format('YYYY-MM-DD HH:mm:ss'));
console.log('한국식 날짜:', now.format('YYYY년 MM월 DD일'));

// ② 특정 날짜 생성
const birthday = dayjs('1990-05-15');
console.log('\n생일:', birthday.format('YYYY년 MM월 DD일'));

// ③ 날짜 계산
const nextWeek = now.add(7, 'day');
const lastMonth = now.subtract(1, 'month');
const nextYear = now.add(1, 'year');

console.log('\n--- 날짜 계산 ---');
console.log('7일 후:', nextWeek.format('YYYY-MM-DD'));
console.log('1달 전:', lastMonth.format('YYYY-MM-DD'));
console.log('1년 후:', nextYear.format('YYYY-MM-DD'));

// ④ 날짜 차이 계산
const today = dayjs();
const newYear = dayjs('2026-01-01');
const daysUntilNewYear = newYear.diff(today, 'day');
console.log('\n새해까지 남은 날:', daysUntilNewYear, '일');

// ⑤ 나이 계산
const birthYear = dayjs('1995-03-20');
const age = today.diff(birthYear, 'year');
console.log(`1995년 3월 20일생의 나이: ${age}세`);

// ⑥ 요일 정보
const days = ['일', '월', '화', '수', '목', '금', '토'];
const todayDayNum = now.day(); // 0(일) ~ 6(토)
console.log('\n오늘 요일:', days[todayDayNum] + '요일');

// ⑦ 유닉스 타임스탬프
console.log('\n유닉스 타임스탬프:', now.unix());
console.log('밀리초 타임스탬프:', now.valueOf());

// ⑧ nodemon 동작 확인용 메시지
console.log('\n서버 시작 시각:', now.format('HH:mm:ss'));
console.log('이 파일을 수정하면 nodemon이 자동으로 재시작합니다!');

Assignment

Assignment 03 — Date dashboard with dayjs

Create an npm project that prints a useful date report.

Setup

npm init -y
npm install dayjs
npm install --save-dev nodemon

Add scripts so npm run dev starts the file with nodemon, and add a .gitignore containing node_modules/ and .env.

Requirements

  1. Print today's date in YYYY-MM-DD and the weekday name.
  2. Print the same date in US format (October 21, 2026) and as YY/MM/DD.
  3. Print the current time as YYYY-MM-DD HH:mm:ss.
  4. Print the date 100 days from today.
  5. Print a D-Day count to the next 25 December (use next year if this year's has passed).
  6. Accept a birthday as process.argv[2] (default 1995-03-20), validate it with dayjs(...).isValid(), then print age in years and days lived.
  7. Print a calendar of the current month, marking Saturdays and Sundays.

Hints

const dayjs = require("dayjs");

const today = dayjs();
console.log(today.format("YYYY-MM-DD"));
console.log(today.add(100, "day").format("YYYY-MM-DD"));

const birthday = dayjs(process.argv[2] || "1995-03-20");
if (!birthday.isValid()) console.log("Use YYYY-MM-DD");
const daysInMonth = today.daysInMonth();
for (let d = 1; d <= daysInMonth; d++) {
  const date = today.date(d);
  console.log(d, date.format("ddd"));
}

Done when

  • npm run dev restarts when you edit the file.
  • An invalid birthday prints a message instead of NaN.
  • The December D-Day is never negative.
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

server.jsJavaScript
// ===================================================
// 과제 03 정답 — 날짜 포맷 변환기
// 실행: npm run dev  또는  node server.js
// ===================================================

// dayjs 패키지 가져오기
const dayjs = require('dayjs');

// 한국 요일 배열 (0=일요일 ~ 6=토요일)
const weekdays = ['일', '월', '화', '수', '목', '금', '토'];

// ① 오늘 날짜 객체 생성
const today = dayjs();

console.log('=== 오늘의 날짜 정보 ===');

// 기본 ISO 형식
console.log('기본 형식:', today.format('YYYY-MM-DD'));

// 한국 형식 + 요일
const weekdayKor = weekdays[today.day()]; // day()는 0~6 반환
console.log(`한국 형식: ${today.format('YYYY년 MM월 DD일')} (${weekdayKor}요일)`);

// 미국 형식: 월 이름 → 간단히 구현
const monthNames = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'
];
const usFormat = `${monthNames[today.month()]} ${today.date()}, ${today.year()}`;
console.log('미국 형식:', usFormat);

// 짧은 형식 (두 자리 연도)
console.log('짧은 형식:', today.format('YY/MM/DD'));

// 날짜 + 시간
console.log('시간 포함:', today.format('YYYY-MM-DD HH:mm:ss'));

// ② D-Day 계산기
console.log('\n=== D-Day 계산기 ===');

// 오늘부터 100일 후
const after100Days = today.add(100, 'day');
console.log('오늘부터 100일 후:', after100Days.format('YYYY-MM-DD'));

// 설날까지 D-Day 계산
const lunar = dayjs('2026-01-29'); // 2026년 설날
const dLunar = lunar.diff(today, 'day'); // diff: 두 날짜의 차이
if (dLunar > 0) {
  console.log(`설날(2026-01-29)까지 D-${dLunar}`);
} else if (dLunar === 0) {
  console.log('오늘이 설날입니다!');
} else {
  console.log(`설날이 ${Math.abs(dLunar)}일 지났습니다.`);
}

// 크리스마스까지 D-Day 계산
// 올해 크리스마스가 지났으면 내년 크리스마스 계산
let christmas = dayjs(`${today.year()}-12-25`);
if (today.isAfter(christmas)) {
  christmas = dayjs(`${today.year() + 1}-12-25`);
}
const dChristmas = christmas.diff(today, 'day');
console.log(`크리스마스(${christmas.format('YYYY-MM-DD')})까지 D-${dChristmas}`);

// ③ 생년월일 계산
console.log('\n=== 생년월일 입력 결과 ===');

// process.argv[2]로 생년월일 받기 (없으면 기본값 사용)
const birthdayStr = process.argv[2] || '1995-03-20';
const birthday = dayjs(birthdayStr);

// 유효한 날짜인지 확인
if (!birthday.isValid()) {
  console.log('유효하지 않은 날짜 형식입니다. YYYY-MM-DD 형식으로 입력하세요.');
} else {
  const age = today.diff(birthday, 'year');           // 만 나이 계산
  const livedDays = today.diff(birthday, 'day');       // 살아온 날 수

  console.log('입력한 생년월일:', birthday.format('YYYY-MM-DD'));
  console.log(`오늘 기준 나이: ${age}세`);
  console.log(`태어난 지: ${livedDays.toLocaleString()}일째`);
}

// ④ 도전: 이번 달 모든 날짜 출력
console.log('\n=== 이번 달 달력 ===');
const daysInMonth = today.daysInMonth(); // 이번 달 총 일수
const yearMonth = today.format('YYYY년 MM월');
console.log(yearMonth);

for (let d = 1; d <= daysInMonth; d++) {
  // 해당 달의 d번째 날 생성
  const date = today.date(d);
  const wd = weekdays[date.day()];
  const isWeekend = date.day() === 0 || date.day() === 6; // 주말 여부
  const mark = isWeekend ? ' ★' : '';  // 주말 표시
  console.log(`  ${d}일 (${wd})${mark}`);
}

Learn this lesson with a mentor

Work through the Build Your Homepage series on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now