Course:Node.js & Express/
Lesson

Now that Node.js is installed, it is time to use it. Unlike a web framework where you are immediately wiring up routes and middlewareWhat is middleware?A function that runs between receiving a request and sending a response. It can check authentication, log data, or modify the request before your main code sees it., running your first script is just two steps: write a .js file and pass it to the node command. This simplicity is intentional, Node.js is a general-purpose runtimeWhat is runtime?The environment that runs your code after it's written. Some languages need a runtime installed on the machine; others (like Go) bake it into the binary., and the entry point is about as bare-bones as it gets.

Hello World

Create a file called app.js in any directory:

console.log('Hello, Node.js!');
console.log('Version:', process.version);
console.log('Platform:', process.platform);

Run it from your terminalWhat is terminal?A text-based interface where you type commands to interact with your computer. Also called the command line or shell.:

node app.js
# Hello, Node.js!
# Version: v20.10.0
# Platform: darwin

That is it. No build step, no compilerWhat is compiler?A program that translates code you write into a language your computer can execute. It also catches errors before your code runs., no configuration. The node command reads the file, passes it to V8What is v8?Google's JavaScript engine that compiles JavaScript to native machine code - it powers both Chrome and Node.js., and executes it.

02

The process object

In the browser, the global object is window. In Node.js it is global, but the most useful global you will reach for constantly is process. It gives you a live view of the running Node.js process.

console.log('Node version:', process.version);      // e.g. v20.10.0
console.log('Platform:', process.platform);         // darwin, linux, win32
console.log('Architecture:', process.arch);         // x64, arm64
console.log('Process ID:', process.pid);            // OS-assigned PID
console.log('Working directory:', process.cwd());   // current directory

Reading command-line arguments with process.argv

process.argv is an array containing everything typed on the command line that invoked Node.js. The first two entries are always fixed:

  • process.argv[0], the full path to the node binaryWhat is binary?A ready-to-run file produced by the compiler. You can send it to any computer and it just works - no install needed.
  • process.argv[1], the full path to the script being run
  • process.argv[2] and beyond, the arguments you actually typed
// greet.js
const name = process.argv[2] || 'World';
console.log(`Hello, ${name}!`);
node greet.js
# Hello, World!

node greet.js Alice
# Hello, Alice!
A common mistake is to expect your first argument at process.argv[0]. Remember: argv[0] is node, argv[1] is your script. Your first real argument lives at argv[2].
03

Environment variables

Environment variables are key-value pairs set in the shell before your script runs. They are the standard way to pass configuration (database URLs, APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. keys, feature flags) without hardcoding values into source code.

// server.js
const port = process.env.PORT || 3000;
const env  = process.env.NODE_ENV || 'development';

console.log(`Starting server on port ${port} in ${env} mode`);

Set them inline when running the script:

PORT=8080 NODE_ENV=production node server.js
# Starting server on port 8080 in production mode

For larger sets of variables, use a .env file with the dotenv package:

npm install dotenv
// Load .env into process.env before anything else
require('dotenv').config();

console.log(process.env.DATABASE_URL);
04

Basic error handling

Node.js uses the same try/catch syntax as browser JavaScript for synchronous code:

try {
  const data = JSON.parse('{invalid json}');
} catch (err) {
  console.error('JSON parse failed:', err.message);
  process.exit(1); // Non-zero exit code signals failure to the shell
}

For truly unexpected errors that slip through, you can register a last-resort handler:

process.on('uncaughtException', (err) => {
  console.error('Uncaught exception:', err);
  process.exit(1);
});
process.exit(0) signals success; any other number signals failure. Build tools and CI pipelines read the exit code to decide whether a step passed or failed. Always exit with a non-zero code when something goes wrong.
05

The interactive REPLWhat is repl?Read-Eval-Print Loop - an interactive prompt where you type code and see the result immediately, like running node with no arguments.

Running node with no arguments drops you into the REPL, an interactive prompt where you can type JavaScript and see results immediately. It is great for prototyping a function or checking how an APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. behaves.

$ node
> const double = x => x * 2
undefined
> double(7)
14
> [1, 2, 3].map(double)
[ 2, 4, 6 ]
> .help      # Lists REPL special commands
> .exit

Special REPL commands start with a dot:

CommandAction
.helpList all REPL commands
.exitExit the REPL (or press Ctrl+D)
.breakAbort a multi-line expression
.clearReset the REPL context
.save filenameSave the current session to a file
.load filenameLoad a file into the REPL
06

npm scripts

Typing node src/index.js every time is repetitive and error-prone. The scripts field in package.json lets you give short names to common commands:

json
{
  "scripts": {
    "start": "node src/index.js",
    "dev":   "node --watch src/index.js",
    "test":  "node --test"
  }
}
npm start       # Runs: node src/index.js
npm run dev     # Runs: node --watch src/index.js  (auto-restarts on changes)
npm test        # Runs: node --test

start and test are special shortcuts, they do not require run. Every other script name does.

07

Debugging

When console.log is not enough, Node.js has a built-in debugger that integrates with Chrome DevTools:

# Start with the inspector open
node --inspect app.js

# Start paused at the first line (useful for catching startup errors)
node --inspect-brk app.js

Then open chrome://inspect in Chrome, click "Open dedicated DevTools for Node", and you get the full DevTools experience, breakpoints, call stackWhat is call stack?The internal mechanism that tracks which function is currently executing and which called it - visible in error stack traces and browser DevTools., variable inspection, for your server-side code.

08

Quick reference

ConceptExample
Run a scriptnode app.js
Pass argumentsnode app.js arg1 arg2
Read first argumentprocess.argv[2]
Read an env variableprocess.env.PORT
Exit successfullyprocess.exit(0)
Exit with failureprocess.exit(1)
Auto-restart on changenode --watch app.js
Open debuggernode --inspect app.js