Stage 3: Backend Essentials

Node.js · Lesson 01

Node.js Basics

What Node.js is, the REPL, the module system and running your first script.

Node.js2 min readFree lesson

JavaScript was born in the browser. Node.js takes the same language, removes the page, and gives it access to the file system, the network and the operating system. Every backend lesson in this track runs on it.

Learning objectives

  • Explain what Node.js is and how it differs from browser JavaScript.
  • Run a script with node, and use the REPL for quick checks.
  • Choose between CommonJS and ES modules.
  • Read command-line arguments and environment variables from process.

1. What Node.js is

Node.js is a runtime built on Chrome's V8 engine. It executes JavaScript outside the browser and adds APIs the browser does not have:

Browser Node.js
document, window fs, path, http
localStorage files on disk, databases
DOM events server requests, process signals

It is single-threaded but non-blocking: slow work (disk, network) is handed to the system and the event loop continues with other callbacks.

2. Install and verify

node --version     # v20.x or newer
npm --version

Start the REPL by typing node with no file. It evaluates one expression at a time — useful for checking a method without creating a file. Exit with .exit or Ctrl+C twice.

3. Running a file

// app.js
console.log("Hello from Node");
node app.js

Node does not have an HTML file to load, so the entry point is whatever file you pass.

4. CommonJS and ES modules

Node supports two module systems.

CommonJS — the default for .js files:

// math.js
function add(a, b) {
  return a + b;
}

module.exports = { add };

// app.js
const { add } = require("./math");
console.log(add(2, 3));

ES modules — add "type": "module" to package.json, or use the .mjs extension:

// math.mjs
export function add(a, b) {
  return a + b;
}

// app.mjs
import { add } from "./math.mjs";

Pick one system per project. Mixing require and import in the same file fails.

5. The process object

process describes the running program.

// node app.js hello world
console.log(process.argv);
// [ 'C:\\Program Files\\nodejs\\node.exe', 'D:\\app.js', 'hello', 'world' ]

const args = process.argv.slice(2); // ['hello', 'world']
console.log(process.env.NODE_ENV); // "development" if set
console.log(process.cwd());        // current working directory
process.exit(1);                    // stop with a failure code

Exit code 0 means success, anything else means failure. Scripts and CI pipelines depend on this.

6. Reading input

For interactive input, Node 18+ ships readline/promises:

import { createInterface } from "node:readline/promises";

const rl = createInterface({ input: process.stdin, output: process.stdout });
const name = await rl.question("Your name: ");
console.log(`Hello, ${name}`);
rl.close();

Common mistakes

  • Running node inside a folder with no entry file — pass the filename.
  • Using window or document in Node; they do not exist.
  • Forgetting that process.argv includes the Node binary and script path.

Practice

Build the command-line calculator in the assignment. It is the smallest possible program that uses arguments, validation, branching and exit codes — the skeleton of every CLI tool.

Example files

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

app.jsJavaScript
// ===================================================
// 강의 01 예제 — Node.js 기초
// 실행: node app.js
//       node app.js 홍길동
// ===================================================

// 1. 기본 출력
console.log('안녕하세요, Node.js 세계!');
console.log('Node.js 버전:', process.version);
console.log('운영체제:', process.platform);

// 2. process.argv로 이름 받아 인사하기
const args = process.argv.slice(2); // 앞의 두 요소(node, 파일명)를 제거

if (args.length > 0) {
  const name = args[0];
  console.log(`\n안녕하세요, ${name}님! Node.js에 오신 것을 환영합니다.`);
} else {
  console.log('\n이름을 입력하지 않았습니다. 사용법: node app.js [이름]');
}

// 3. 현재 작업 디렉토리와 환경 정보 출력
console.log('\n--- 실행 환경 정보 ---');
console.log('작업 디렉토리:', process.cwd());
console.log('Node.js 버전:', process.versions.node);

// 4. 간단한 CLI 계산 스크립트 (덤으로 보여주는 예시)
console.log('\n--- 간단한 계산 ---');
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
const avg = sum / numbers.length;
console.log('숫자 목록:', numbers.join(', '));
console.log('합계:', sum);
console.log('평균:', avg);

// 5. 모듈 시스템 데모 (CommonJS)
// 다른 파일에서 사용할 수 있도록 내보내기 예시
const greet = (name) => `안녕하세요, ${name}님!`;
const farewell = (name) => `안녕히 가세요, ${name}님!`;

module.exports = { greet, farewell };

// 직접 실행 시에만 아래 코드 실행 (모듈로 불렸을 때는 실행 안 됨)
if (require.main === module) {
  console.log('\n--- 함수 테스트 ---');
  console.log(greet('개발자'));
  console.log(farewell('개발자'));
}

Assignment

Assignment 01 — Command-line calculator

Build a calculator that reads its operands from the terminal.

node app.js 10 + 20     # 10 + 20 = 30
node app.js 7 / 2       # 7 / 2 = 3.50
node app.js 4 x 5       # error: unsupported operator

Requirements

  1. Read exactly three arguments with process.argv.slice(2): number, operator, number.
  2. Support +, -, * and /.
  3. If fewer than three arguments are given, print a usage line and exit with code 1.
  4. If either operand is not a number (Number.isNaN), print an error and exit 1.
  5. Division by zero must be rejected with a clear message, not Infinity.
  6. An unknown operator prints the supported list and exits 1.
  7. Print integers without decimals and other results with two decimals.

Hints

const args = process.argv.slice(2);
const num1 = Number(args[0]);
const operator = args[1];
const num2 = Number(args[2]);

if (Number.isNaN(num1) || Number.isNaN(num2)) {
  console.error("Both operands must be numbers.");
  process.exit(1);
}
const display = Number.isInteger(result) ? result : result.toFixed(2);
console.log(`${num1} ${operator} ${num2} = ${display}`);

Done when

  • Every error path prints a message to stderr and returns a non-zero exit code.
  • node app.js 10 + 20 prints 10 + 20 = 30.
  • node app.js 7 / 2 prints 7 / 2 = 3.50.
Show the reference solution

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

app.jsJavaScript
// ===================================================
// 과제 01 정답 — CLI 계산기
// 실행: node app.js 10 + 20
// ===================================================

// process.argv 구조:
// [0] node 실행 경로
// [1] 현재 파일 경로
// [2] 첫 번째 인수 (숫자1)
// [3] 두 번째 인수 (연산자)
// [4] 세 번째 인수 (숫자2)
const args = process.argv.slice(2); // 앞의 두 요소 제거

// ① 인수 개수 검사 — 3개가 아니면 사용법 안내
if (args.length < 3) {
  console.error('사용법: node app.js 숫자1 연산자 숫자2');
  console.error('예시:   node app.js 10 + 20');
  process.exit(1); // 비정상 종료 (exit code 1)
}

// ② 인수 파싱
const num1 = Number(args[0]);   // 첫 번째 숫자
const operator = args[1];       // 연산자 (+, -, *, /)
const num2 = Number(args[2]);   // 두 번째 숫자

// ③ 숫자 유효성 검사 — NaN이면 오류 출력
if (isNaN(num1) || isNaN(num2)) {
  console.error('오류: 숫자만 입력할 수 있습니다.');
  process.exit(1);
}

// ④ 연산자별 계산
let result; // 계산 결과를 저장할 변수

switch (operator) {
  case '+':
    result = num1 + num2;
    break;

  case '-':
    result = num1 - num2;
    break;

  case '*':
    result = num1 * num2;
    break;

  case '/':
    // 0으로 나누기 예외 처리
    if (num2 === 0) {
      console.error('오류: 0으로 나눌 수 없습니다.');
      process.exit(1);
    }
    result = num1 / num2;
    break;

  default:
    // 지원하지 않는 연산자 처리
    console.error(`오류: '${operator}'는 지원하지 않는 연산자입니다.`);
    console.error('지원 연산자: + - * /');
    process.exit(1);
}

// ⑤ 결과 출력 — 소수점이 있으면 최대 2자리까지만 표시
const displayResult = Number.isInteger(result)
  ? result
  : result.toFixed(2);

console.log(`${num1} ${operator} ${num2} = ${displayResult}`);

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