Node.js Fundamentals and Runtime
Understand what Node.js is, how it works, why it is different from browser JavaScript, and how to build and execute your first Node.js programs.
What Is Node.js?
Node.js is a JavaScript runtime built on the V8 JavaScript engine. It allows JavaScript to execute outside the browser, making it possible to build servers, APIs, command-line tools, background workers, automation scripts, and real-time applications.
Unlike browser JavaScript, Node.js provides APIs for operating-system and server-side capabilities such as the file system, networking, processes, environment variables, streams, and TCP sockets.
Node.js is especially effective for I/O-heavy workloads because applications can initiate asynchronous operations without blocking the JavaScript execution thread.
JavaScript is the language. Node.js is a runtime that provides an environment and APIs for executing JavaScript outside the browser.
console.log('Hello from Node.js');app.js and execute it with node app.js. Node.js runs the JavaScript without requiring a browser.- Node.js is a JavaScript runtime, not a new programming language.
- Node.js is powered by V8 and provides server-side APIs through the Node.js runtime.
- Its asynchronous architecture makes it well suited to I/O-heavy applications.
What is Node.js?
Installing Node.js and Using the Node CLI
The node command is the primary CLI for executing JavaScript files and interacting with the Node.js runtime. You can verify your installation using node --version and npm --version.
Node also provides a REPL, which is useful for experimenting with JavaScript and Node APIs interactively.
Using a Node.js version manager such as nvm makes it easier to switch between Node.js versions for different projects.
node --version
npm --version
node
node app.jsnode starts the REPL, and node app.js executes a JavaScript file.- Use
node filename.jsto execute a Node.js application. - The Node REPL is useful for quickly testing JavaScript expressions.
- Keep project Node.js versions consistent across development and production.
Which command executes `server.js`?
Global Objects and the Process Object
Node.js provides useful global objects and variables such as process, console, Buffer, setTimeout, and globalThis. The process object provides information and controls for the currently running Node.js process.
Common properties include process.env for environment variables, process.argv for command-line arguments, and process.exit() for terminating a process.
console.log('Arguments:', process.argv.slice(2));
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('PID:', process.pid);- Use
process.envfor runtime configuration. - Use
process.argvto access command-line arguments. - Avoid hardcoding secrets directly in source code.
Where are environment variables accessed in Node.js?