What it is
Node.js is a JavaScript runtime environment that allows you to execute JavaScript code outside of a web browser, commonly used for building server-side applications, command-line tools, and more.
Installation
Linux (using NVM - Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc # or ~/.zshrc, ~/.profile, etc.
nvm install node # Installs the latest stable version
nvm install 18 # Installs the latest 18.x version
nvm use 18 # Uses version 18.x for the current shell
macOS (using NVM)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.zshrc # or ~/.bash_profile, etc.
nvm install node
nvm install 18
nvm use 18
Windows (using NVM for Windows)
Download the installer from https://github.com/coreybutler/nvm-windows/releases and run it. After installation, open a new command prompt and run:
nvm install latest
nvm install 18
nvm use 18
Global Installation (less recommended than NVM)
Download installers from https://nodejs.org/.
Core Concepts
- Event Loop: The mechanism that allows Node.js to perform non-blocking I/O operations despite being single-threaded. It handles callbacks, promises, and async/await.
- Modules: Node.js uses the CommonJS module system (
require/module.exports) by default, though ES Modules (import/export) are now supported with specific configurations. - npm/Yarn: Package managers for Node.js, used to install and manage external libraries (packages).
Commands / Usage
Running a JavaScript file
node my_script.js
Executes the specified JavaScript file.
Running code directly
// In your terminal
node
> console.log('Hello, Node!');
Hello, Node!
undefined
> .exit
Starts an interactive Node.js REPL (Read-Eval-Print Loop) where you can type and execute JavaScript code. Type .exit to quit.
Running code from stdin
echo "console.log('Piped input!');" | node
Executes JavaScript code piped from standard input.
Running a module as a script
node -e "console.log(process.version);"
Executes the given JavaScript code string.
Inspecting code (Debugging)
node --inspect my_script.js
Starts the script with the V8 inspector enabled, allowing you to connect a debugger (like Chrome DevTools).
node --inspect-brk my_script.js
Same as --inspect, but pauses execution on the very first line of the script.
Version information
node -v
Prints the Node.js version.
npm -v
Prints the npm version.
Help
node --help
Displays help information for Node.js command-line options.
Common Patterns
Running a server
// server.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Run it:
node server.js
Starts a simple HTTP server.
Using package.json
// package.json
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
Install dependencies:
npm install
Run scripts defined in package.json:
npm start
Executes node index.js.
npm run dev
Executes nodemon index.js (requires nodemon to be installed as a dev dependency).
Executing scripts with arguments
// greet.js
const name = process.argv[2] || 'World';
console.log(`Hello, ${name}!`);
Run it:
node greet.js Alice
Output: Hello, Alice!
Using ES Modules
Create package.json with "type": "module" or save your file with a .mjs extension.
// index.mjs
import fs from 'fs/promises';
async function readFileContent(filePath) {
try {
const data = await fs.readFile(filePath, 'utf8');
console.log(data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFileContent('example.txt');
Run it:
node index.mjs
Gotchas
- Blocking I/O: Node.js is single-threaded. Long-running synchronous operations (like heavy computations or reading very large files synchronously) will block the entire event loop, making your application unresponsive. Always prefer asynchronous operations.
requirevsimport: Mixing CommonJS (require) and ES Modules (import) can be tricky. Ensure yourpackage.jsonhas"type": "module"or use.mjsfiles for ES Modules, and.cjsfor CommonJS if needed.- Global Variables: Be cautious with global variables. They can lead to unexpected behavior, especially in concurrent requests. Use
letandconstappropriately. - Error Handling: Uncaught exceptions can crash your Node.js process. Implement robust error handling with
try...catchblocks for synchronous code and.catch()for Promises, or useprocess.on('uncaughtException')sparingly for critical logging before exiting. process.argvIndexing:process.argv[0]is the Node.js executable path,process.argv[1]is the script path. Your actual arguments start fromprocess.argv[2].- NVM Path Issues: If
nodeornpmcommands aren’t found after installing with NVM, ensure you’ve sourced your shell profile correctly (e.g.,source ~/.bashrc) or restarted your terminal.