JavaScript • Getting Started and Tooling

Running with Node.js — Run JavaScript with Node.js (node file.js) (conceptual)

Learn how Node.js lets you run JavaScript outside the browser, turning it into a powerful general-purpose language.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

For most of its early life, JavaScript was trapped inside the web browser. Developers could use it to make buttons change color or validate a form, but the moment you closed the browser, JavaScript had no home. Every other popular language — Python, Java, C++ — could run directly on your computer's operating system, reading files, building servers, and powering desktop apps. JavaScript simply couldn't. This limitation bothered a growing community of developers who loved the language's flexibility but wanted to do more with it.

The breakthrough came in 2009 when a software engineer named Ryan Dahl introduced Node.js, a runtime environment that took JavaScript out of the browser and placed it squarely on the desktop, the server, and eventually everywhere. Dahl built Node.js on top of Google Chrome's blazing-fast V8 engine, the same engine that makes Chrome execute JavaScript so quickly. The result was a tool that could run any JavaScript file directly from the command line with a simple command: node file.js.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript in just 10 days at Netscape. It is designed exclusively for the browser to add interactivity to web pages.

2008 • Google Releases the V8 Engine

Google builds the V8 JavaScript engine for Chrome. It compiles JavaScript directly to machine code, making execution dramatically faster than earlier interpreters.

2009 • Node.js Launches

Ryan Dahl unveils Node.js at the JSConf EU conference, allowing developers to run JavaScript outside the browser for the first time at scale.

2010 • npm Is Introduced

The Node Package Manager (npm) launches, giving developers access to thousands of reusable JavaScript libraries. It becomes the world's largest software registry.

2023+ • Node.js Powers the Modern Web

Major companies like Netflix, PayPal, and NASA use Node.js in production. It is one of the most widely-used server-side platforms in the world.

The central question Node.js answers is straightforward: How can we run JavaScript code without a browser? Understanding this question — and its answer — is the first step toward using JavaScript as a full-fledged programming language for everything from web servers to command-line tools.

SECTION 2

Core Principles & Definitions

Before you type node file.js into a terminal, it helps to understand a few foundational ideas. These concepts explain what Node.js actually is, how it relates to the browser, and why it matters for modern software development.

1

Runtime Environment

A runtime environment is the software layer that executes your code. The browser is one runtime for JavaScript; Node.js is another. Each runtime provides different built-in capabilities.
2

The V8 Engine

At its core, Node.js uses Google's V8 engine to read and execute JavaScript. V8 compiles JavaScript into fast machine code, which is why Node.js can handle demanding tasks like running a web server.
3

The Command Line (Terminal)

The command line is a text-based interface where you type commands to interact with your computer. Instead of clicking icons, you type instructions like node app.js to run programs.
4

Scripts and .js Files

A JavaScript script is simply a plain-text file ending in .js that contains JavaScript instructions. Node.js reads this file from top to bottom and executes each statement in order.
5

Server-Side vs. Client-Side

Client-side JavaScript runs in the user's browser. Server-side JavaScript runs on a remote computer (server) using Node.js. The same language works in both places, but the available tools differ.
✦

KEY TAKEAWAY

Think of JavaScript as a musician who originally could only perform in one specific concert hall (the browser). Node.js is like a portable stage — it lets that musician perform anywhere: in the park, at a stadium, or in a recording studio. The musician's talent (JavaScript) hasn't changed, but now there are no venue restrictions.

SECTION 3

Visual Explanation — How Node.js Executes Your Code

The following diagram shows what happens behind the scenes when you type node file.js into your terminal. The journey starts with your plain-text JavaScript file and ends with actual results displayed on screen.

How node file.js WorksYOUR FILEapp.jsconsole.log(...)TERMINAL$ node app.jsYou type the commandNODE.JS RUNTIMEV8 ENGINECompiles JS → MachineCPUExecutesmachine codeOUTPUTHello, world!Step-by-Step Flow1. You write JavaScript code in a .js file using a text editor.2. You open a terminal and type: node yourfile.js3. Node.js reads the file and passes it to the V8 engine for compilation.4. V8 compiles JavaScript into machine code, and the CPU executes it. Output appears in the terminal.
The diagram traces the path from your .js file through the terminal, into the Node.js runtime (which contains the V8 engine), and finally to the CPU, which executes the compiled machine code. The output is displayed back in the terminal.

Notice that the browser is completely absent from this process. When you use Node.js, there is no HTML page, no web address, and no browser window. Instead, everything happens through the command line interface. This is what makes Node.js fundamentally different from the JavaScript you may have seen in web development tutorials — it's the same language, but running in a completely different environment.

SECTION 4

How Node.js Works Under the Hood

When you run node file.js, several important things happen in sequence. Understanding this process helps you debug errors, predict behavior, and appreciate why Node.js is structured the way it is.

Phase 1 — File Reading

Node.js first locates the file you specified. If you typed node app.js, it looks for a file named app.js in your current directory. If the file doesn't exist, Node.js throws a MODULE_NOT_FOUND error and stops immediately. The file must contain valid JavaScript — it cannot be an image, a Word document, or random text.

Phase 2 — Parsing and Compilation

Next, the V8 engine parses your code, checking for syntax errors. If it finds a mistake — like a missing parenthesis or an unexpected keyword — it throws a SyntaxError before running anything. If the syntax is correct, V8 compiles the JavaScript into optimized machine code — the low-level instructions that your computer's processor (CPU) can understand directly.

Phase 3 — Execution

The compiled code executes line by line from the top of your file to the bottom. Statements like console.log() produce output in the terminal, variable assignments store data in memory, and function calls jump to specific blocks of code. When the last line finishes, the Node.js process exits and you return to the terminal prompt.

Phase 4 — Built-In APIs

Unlike the browser, Node.js does not provide a document object or a window object. Instead, it offers its own set of built-in modules — like fs for reading and writing files, http for creating web servers, and path for working with file paths. These modules give JavaScript the power to interact with the operating system, which it could never do inside a browser.

⚠

Important Difference

In the browser, JavaScript has access to document.getElementById() and alert(). In Node.js, these do not exist. Instead, you gain tools like require('fs') and process.argv. Same language, different toolkit.

SECTION 5

Browser JavaScript vs. Node.js JavaScript

One of the trickiest things for newcomers to understand is that JavaScript behaves slightly differently depending on where it runs. The language syntax is identical — variables, loops, functions, and objects work the same way. However, the environment surrounding the language changes what you can do.

Browser vs. Node.js Environments🌐 BROWSERJavaScript Engine (V8, SpiderMonkey)window, document, DOMfetch(), localStoragealert(), prompt()❌ Cannot access file system❌ Cannot create serversRuns inside HTML pages⬡ NODE.JSJavaScript Engine (V8)global, processrequire('fs'), require('http')console.log(), process.argv✅ Full file system access✅ Can create HTTP serversRuns from the command line⟷Same Language, Different Tools
Both environments use a JavaScript engine at their core, but the browser provides DOM-related APIs (window, document) while Node.js provides server and file system APIs (fs, http, process).
FeatureBrowserNode.js
Global objectwindowglobal
Manipulate HTML✅ Yes (DOM)❌ No
Read/write files❌ No✅ Yes (fs module)
Create a web server❌ No✅ Yes (http module)
console.log()✅ Browser console✅ Terminal output
How you run codeOpen HTML file in browserType node file.js in terminal

Key differences between browser and Node.js environments

SECTION 6

Worked Example — Your First Node.js Program

Let's walk through the complete process of creating and running a JavaScript file with Node.js. This example assumes Node.js is already installed on your computer. We'll build a small program that greets the user and performs a calculation.

Creating and Running a Node.js Script

  1. 1

    Step 1 — Create a new file

    Open any text editor (VS Code, Notepad, Sublime Text, etc.) and create a new file. Save it as greet.js. The .js extension tells Node.js that this file contains JavaScript code.
    File created: greet.js
  2. 2

    Step 2 — Write JavaScript code

    Type the following lines into your file: let name = "Alex"; let year = 2025; let birthYear = year - 16; console.log("Hello, " + name + "!"); console.log("You were probably born around " + birthYear + "."); This code declares variables, performs arithmetic, and uses console.log() to print results.
    Code written with 5 lines of JavaScript
  3. 3

    Step 3 — Open the terminal

    Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux, or the integrated terminal in VS Code). Navigate to the folder where you saved greet.js using the cd command. For example: cd Desktop if the file is on your Desktop.
    Terminal open and navigated to correct folder
  4. 4

    Step 4 — Run the file with Node.js

    Type the command node greet.js and press Enter. Node.js reads your file, compiles it through the V8 engine, and executes it. The word node tells your computer to use Node.js as the runtime, and greet.js tells it which file to run.
    Command: node greet.js
  5. 5

    Step 5 — Read the output

    The terminal displays the output from your two console.log() statements. After the output prints, the Node.js process automatically exits and you see your terminal prompt again, ready for the next command.
    Output: Hello, Alex! and You were probably born around 2009.
💡

Pro Tip

If you see an error like 'node' is not recognized, it means Node.js hasn't been installed yet. Visit nodejs.org to download and install it. Once installed, restart your terminal and try again.

SECTION 7

Strengths & Limitations of Node.js

Node.js is a powerful tool, but like any technology, it has strengths and limitations. Understanding both helps you decide when Node.js is the right choice and when another approach might work better.

Strengths ✅Limitations ⚠️
One language for everything — use JavaScript for both front-end (browser) and back-end (server).No access to browser-specific features like the DOM, so you can't directly manipulate web pages.
Extremely fast execution thanks to the V8 engine's just-in-time compilation.Single-threaded by default — heavy computation can block other tasks if not managed carefully.
Massive ecosystem of packages available through npm (over 2 million packages).Package quality varies widely — beginners can install poorly maintained or insecure packages.
Cross-platform — works on Windows, macOS, and Linux without changes to your code.Not ideal for CPU-intensive tasks like video encoding or complex scientific computation.
Active community with extensive documentation, tutorials, and Stack Overflow answers.The rapid pace of updates can sometimes create compatibility issues between versions.

Strengths and limitations of using Node.js for running JavaScript

✦

KEY TAKEAWAY

Think of Node.js like a Swiss Army knife. It's incredibly versatile and great for a wide range of tasks — building servers, creating command-line tools, automating workflows. But you wouldn't use a Swiss Army knife to chop down a tree. Similarly, Node.js excels at I/O tasks (reading files, handling web requests) but is less suited for heavy mathematical computation where languages like C++ or Rust shine.

SECTION 8

Connecting to Advanced Concepts

Running a single file with node file.js is just the starting point. As you grow more comfortable with Node.js, you'll encounter a whole ecosystem of tools and patterns that build on this foundation. Understanding where the basics end and advanced topics begin helps you chart a clear learning path.

What You Know NowWhat Comes Next
Running a single .js file with node file.jsRunning multi-file projects with modules (require() and import)
Using console.log() for outputUsing Node.js built-in modules (fs, http, path) for real-world tasks
Running code synchronously (top to bottom)Understanding asynchronous code: callbacks, Promises, and async/await
Writing all code from scratchInstalling and using third-party packages with npm
Running scripts manually in the terminalAutomating tasks with npm scripts and build tools

Your learning journey from basics to advanced Node.js

One of the most exciting next steps is learning about npm (Node Package Manager), which lets you install pre-built code libraries that other developers have shared. Imagine needing to build a web server — instead of writing hundreds of lines of code from scratch, you can install a package called Express.js with a single command and build your server in under 10 lines. This is the power of the Node.js ecosystem, and it all starts with the simple node file.js command you've learned today.

ℹ

Looking Ahead

Other modern JavaScript runtimes like Deno and Bun have emerged as alternatives to Node.js. They follow similar principles — running JS outside the browser via a command — but offer different features like built-in TypeScript support and enhanced security. Knowing Node.js prepares you to understand these tools, too.

SECTION 9

Practice Problems

Test your understanding of Node.js concepts with these five problems. They start with basic recall and build toward more challenging critical thinking.

Question 1: CONCEPTUAL

What is the purpose of Node.js? Why can't you simply double-click a .js file to run it?
Show answer
Node.js is a runtime environment that allows JavaScript to run outside the browser. You can't simply double-click a .js file because your operating system doesn't natively understand JavaScript — it needs a runtime to interpret and execute the code. Without Node.js (or a browser), the operating system has no idea what to do with JavaScript syntax. Node.js provides the V8 engine and system-level APIs needed to process the file. You must use the command node file.js in a terminal to explicitly tell your computer to use Node.js as the interpreter.

Question 2: BASIC CALCULATION

You have a file called math.js that contains the following code: let a = 15; let b = 4; console.log(a + b); console.log(a * b); console.log(a % b); What output would you see in the terminal after running node math.js?
Show answer
The output would be three lines: 19, 60, and 3. The first console.log prints 15 + 4 = 19. The second prints 15 × 4 = 60. The third uses the modulo operator (%), which returns the remainder of division: 15 ÷ 4 = 3 remainder 3, so a % b outputs 3. Node.js executes each line from top to bottom, and each console.log prints its result on a new line in the terminal.

Question 3: INTERMEDIATE

A student writes the following code in test.js: document.getElementById("title").textContent = "Hello!"; console.log("Done!"); They run node test.js and get an error. Explain why the error occurs and what the student should change.
Show answer
The error occurs because document is a browser-only object that represents the HTML page. Node.js does not provide a document object because there is no HTML page or DOM in the Node.js environment. When Node.js encounters document.getElementById, it throws a ReferenceError because document is undefined. The student should either run this code in a browser (inside an HTML file with a <script> tag), or rewrite the code to use Node.js-compatible features like console.log("Hello!") instead of DOM manipulation.

Question 4: APPLIED

Imagine you're building a simple homework tracker. You want to create a Node.js script called homework.js that stores three assignments in an array and prints each one. Write the code you would put in the file and the terminal command to run it.
Show answer
The code could look like this: let assignments = ["Math Ch.5 Problems", "English Essay Draft", "CS Node.js Lab"]; for (let i = 0; i < assignments.length; i++) { console.log((i + 1) + ". " + assignments[i]); } You would save this as homework.js and run it by typing node homework.js in the terminal. The output would be: 1. Math Ch.5 Problems 2. English Essay Draft 3. CS Node.js Lab This demonstrates how Node.js can run practical, everyday scripts that process data and display formatted output.

Question 5: CRITICAL THINKING

A company wants to build a web application where users fill out a form in their browser, and the data is saved to a file on the server. Explain how both browser JavaScript and Node.js would be needed in this scenario. Which parts of the application would each environment handle, and why can't either one do the entire job alone?
Show answer
This scenario requires both environments because each has capabilities the other lacks. Browser JavaScript handles the client side: it renders the form on the web page using DOM manipulation, validates user input in real time, and sends the submitted data to the server using a network request (like fetch). However, browser JavaScript cannot save files to the server's hard drive — it's sandboxed for security reasons. Node.js handles the server side: it receives the incoming data from the browser, processes it, and uses the fs module to write that data to a file on the server's file system. Node.js cannot render HTML forms or respond to button clicks in a user's browser — it has no DOM. Together, they form a complete system: browser JS manages the user interface, and Node.js manages server logic and data storage. This is the foundational architecture of modern web applications, and it illustrates why Node.js was such a breakthrough — it allowed developers to use the same language on both sides.

SUMMARY

Lesson Summary

Summary

Node.js is a runtime environment that lets you run JavaScript outside the browser, directly from the command line. Created by Ryan Dahl in 2009, it is built on Google's V8 engine, which compiles JavaScript into fast machine code. The basic workflow is simple: write your JavaScript in a .js file, open a terminal, and type node file.js to execute it.

While browser JavaScript and Node.js share the same core language, they offer different tools. The browser provides the DOM for manipulating web pages, whereas Node.js provides modules like fs and http for file system access and web server creation. Understanding this distinction is crucial as you progress toward building full-stack applications, working with npm packages, and mastering asynchronous programming — all of which build on the foundational skill of running JavaScript with Node.js.

Varsity Tutors • JavaScript • Running with Node.js — Run JavaScript with Node.js (node file.js) (conceptual)