HTML & JS Topic

Node.js Basics

JavaScript Recap for Node.js

Key Differences from Browser JS:

  • No DOM - No document, window, or browser APIs

  • Different Global Object - global instead of window

  • Module System - CommonJS (require()) by default

  • File System Access - Can read/write files

  • Built-in Modules - fs, http, path, etc.

ES6+ Features You'll Use Often:

javascript

// Arrow functions
const add = (a, b) => a + b;

// Template literals
console.log(`Server running on port ${PORT}`);

// Destructuring
const { readFile, writeFile } = require('fs');

// Spread/Rest operators
const config = { port: 3000, ...defaultConfig };

// Promises & Async/Await
const fetchData = async () => {
  try {
    const data = await someAsyncOperation();
    return data;
  } catch (error) {
    console.error(error);
  }
};

// ES Modules (alternative to CommonJS)
import express from 'express'; // Instead of: const express = require('express')

Global Objects in Node.js

global Object:

  • Similar to window in browsers

  • Properties attached to global are available everywhere

  • Don't pollute the global namespace!

Important Global Objects & Variables:

  1. __dirname - Absolute path to the directory containing the current file

javascript

console.log(__dirname);
// Output: /Users/username/projects/myapp/src
  1. __filename - Absolute path to the current file

javascript

console.log(__filename);
// Output: /Users/username/projects/myapp/src/app.js
  1. process - Information and control over the current Node.js process

javascript

// Get environment variables
console.log(process.env.NODE_ENV);

// Command line arguments
console.log(process.argv); // ['node', 'app.js', 'arg1', 'arg2']

// Current working directory
console.log(process.cwd()); // Different from __dirname!

// Exit the process
process.exit(0); // 0 = success, non-zero = error

// Standard I/O streams
process.stdin;   // Standard input
process.stdout;  // Standard output
process.stderr;  // Standard error

// Platform information
console.log(process.platform); // 'darwin', 'win32', 'linux'
console.log(process.version);  // Node.js version
console.log(process.pid);      // Process ID

// Memory usage
console.log(process.memoryUsage());
  1. console - Similar to browser but with extra methods

javascript

console.log('Standard log');
console.error('Error message');
console.warn('Warning');
console.table([{name: 'John', age: 30}, {name: 'Jane', age: 25}]);
console.time('timer'); console.timeEnd('timer'); // Performance timing
  1. module, exports, require - CommonJS module system

javascript

// module.exports and exports reference the same object
exports.myFunction = () => {};
// Equivalent to: module.exports.myFunction = () => {};

// require() caches modules - second call returns cached version
const fs = require('fs');

globalThis (ES2020):

javascript

// Works in both Node.js and browsers
globalThis.setTimeout === setTimeout; // true

The Node.js REPL

REPL = Read-Eval-Print-Loop - Interactive Node.js shell

Starting REPL:

bash

# Just type 'node' without arguments
node

REPL Commands & Features:

javascript

> 2 + 2            // Simple calculations
4

> const name = 'Node.js'  // Variable declaration

> .help             // Show all commands
> .break            // Exit multi-line input
> .clear            // Clear context
> .exit             // Exit REPL (or Ctrl+D twice)
> .save filename.js // Save session to file
> .load filename.js // Load file into REPL
> .editor           // Enter editor mode (Ctrl+D to save, Ctrl+C to cancel)

// Special variable '_' contains last result
> 5 + 5
10
> _ * 2
20

// Multi-line input (automatic on brackets)
> function hello() {
... console.log('Hello!');
... }

Useful REPL Features:

  1. Tab Completion - Press Tab for autocomplete

  2. Up/Down Arrows - Command history

  3. Run JavaScript files from REPL:

javascript

> .load app.js      // Load and execute file

Understanding package.json

The package.json is the manifest file for Node.js projects.

Creating package.json:

bash

npm init              # Interactive setup
npm init -y           # Accept all defaults
npm init --scope=@username  # Create scoped package

Key Fields in package.json:

json

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "A sample Node.js project",
  "main": "index.js",           // Entry point
  
  "scripts": {                  // Custom npm commands
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest",
    "build": "tsc"
  },
  
  "keywords": ["node", "example"],
  "author": "Your Name",
  "license": "MIT",
  
  "dependencies": {             // Production dependencies
    "express": "^4.18.0",
    "mongoose": "^6.0.0"
  },
  
  "devDependencies": {          // Development dependencies
    "nodemon": "^2.0.0",
    "jest": "^28.0.0"
  },
  
  "engines": {                  // Required Node.js version
    "node": ">=14.0.0",
    "npm": ">=6.0.0"
  },
  
  "repository": {
    "type": "git",
    "url": "https://github.com/username/repo.git"
  },
  
  "bugs": {
    "url": "https://github.com/username/repo/issues"
  },
  
  "homepage": "https://github.com/username/repo#readme"
}

Versioning Syntax (Semantic Versioning):

json

"dependencies": {
  "express": "^4.18.0",    // Accept 4.x.x (major version locked)
  "lodash": "~4.17.21",    // Accept 4.17.x (minor version locked)
  "react": "16.13.1",      // Exact version only
  "moment": "*",           // Any version (dangerous!)
  "axios": "latest"        // Latest version
}

Useful Commands:

bash

npm list              # Show installed dependencies
npm outdated          # Check for outdated packages
npm audit             # Security audit
npm audit fix         # Fix security vulnerabilities
npm version patch     # Bump patch version (1.0.0 → 1.0.1)
npm version minor     # Bump minor version (1.0.0 → 1.1.0)
npm version major     # Bump major version (1.0.0 → 2.0.0)

npm vs npx

npm (Node Package Manager):

  • Installs packages globally or locally

  • Manages dependencies in node_modules

  • Runs scripts defined in package.json

bash

# Package management
npm install express          # Install locally (adds to package.json)
npm install -g nodemon       # Install globally
npm uninstall express        # Remove package
npm update express           # Update package

# Run scripts from package.json
npm start
npm run dev
npm test

npx (Node Package Execute):

  • Executes packages without permanent installation

  • Runs binaries from locally installed packages

  • Downloads and runs packages temporarily

bash

# Run a package without installing it
npx create-react-app my-app          # One-time use
npx jest                             # Run locally installed Jest
npx cowsay "Hello World"             # Fun temporary packages

# Execute specific version
npx express@4.16.0 --version

# Clear npx cache
npx clear-npx-cache

Key Differences:

Feature npm npx
Primary Purpose Install packages Execute packages
Persistence Installs to node_modules or global Temporary execution
Binaries Installs binaries, need path to run Directly executes binaries
Package.json Required for local installs Not required for one-time use
Common Use npm install, npm start npx create-*, run tools

Practical Examples:

bash

# Before npx: Had to install globally first
npm install -g create-react-app
create-react-app my-app

# With npx: No global installation needed
npx create-react-app my-app

# Run different Node.js versions
npx node@14 --version
npx node@16 script.js

# Execute TypeScript compiler without installing
npx tsc --init

When to Use Which:

  • Use npm when you need a package for your project (dependencies)

  • Use npx when you need to execute a tool/CLI temporarily

  • Use npx for project scaffolding (create-react-app, vite, etc.)

  • Use npm for managing project dependencies and scripts

Bonus: Package Lock Files

bash

# package-lock.json or yarn.lock or pnpm-lock.yaml
# These files lock exact dependency versions
# Commit them to version control for reproducible builds

This foundation helps understand how Node.js projects are structured and managed!

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?