Node.js Cheat Sheet & Command Reference
A beginner-friendly Node.js cheat sheet. Copy-paste examples, common mistakes, syntax guides, and interview questions for backend developers.
What is Node.js?
Node.js is an open-source runtime environment that allows you to run JavaScript on a server (outside the browser). It is built on Chrome's V8 JavaScript engine.
Syntax
// Run a file using the terminal
node filename.jsExample
// Create a file called app.js
console.log("Hello from the server!");
// In terminal: node app.jsCommon Mistake
Trying to use browser APIs like `window` or `document`. These do not exist in Node.js.
Best Practice
Always use `nvm` (Node Version Manager) to install and manage your Node.js versions.
Interview Tip
Be prepared to explain that Node.js is NOT a framework or a language. It is a runtime environment.
File System (fs module)
The `fs` module allows you to interact with the file system on your computer to read, create, update, or delete files.
Syntax
const fs = require('fs');
fs.readFileSync('path'); // Synchronous
fs.readFile('path', callback); // AsynchronousExample
const fs = require('fs');
// Writing to a file
fs.writeFileSync('note.txt', 'Hello World!');
// Reading from a file
const data = fs.readFileSync('note.txt', 'utf8');
console.log(data); // Hello World!Common Mistake
Using Synchronous methods (`readFileSync`) in a web server environment. It will block the entire server from handling other requests.
Best Practice
Use the promise-based version of the fs module: `const fs = require('fs/promises');` along with async/await.
Interview Tip
Explain the difference between blocking and non-blocking code using `readFileSync` vs `readFile`.
Express.js Setup
Express is the most popular, fast, and minimalist web framework for Node.js. It handles routing and HTTP requests easily.
Syntax
// Terminal: npm install express
const express = require('express');
const app = express();Example
const express = require('express');
const app = express();
// Define a route
app.get('/', (req, res) => {
res.send('Welcome to my API!');
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});Common Mistake
Forgetting to start the server using `app.listen()`, or trying to start it on a port that is already in use.
Best Practice
Use a tool like `nodemon` during development so your server automatically restarts when you save a file.
Interview Tip
What is middleware in Express? It is a function that has access to the request object, response object, and the next middleware function.
Building REST APIs
REST APIs allow a client (like a React app) to communicate with your Node.js server to get or modify data using HTTP methods.
Syntax
app.get('/api/users', getObject);
app.post('/api/users', createObject);Example
app.use(express.json()); // Allows parsing JSON body
app.post('/api/users', (req, res) => {
const newUser = req.body;
// Save to database logic here...
res.status(201).json({
message: 'User created',
data: newUser
});
});Common Mistake
Forgetting to include `app.use(express.json())`. Without it, `req.body` will be `undefined`.
Best Practice
Use proper HTTP status codes. Return `200` for OK, `201` for Created, `404` for Not Found, and `500` for Server Errors.
Interview Tip
Explain the difference between POST, PUT, and PATCH HTTP methods.
Environment Variables
Environment variables keep sensitive information (like Database Passwords or API Keys) out of your code.
Syntax
// npm install dotenv
require('dotenv').config();
const key = process.env.SECRET_KEY;Example
// Inside a .env file:
// DB_PASS=supersecret123
// Inside app.js
require('dotenv').config();
const dbPassword = process.env.DB_PASS;
console.log(dbPassword); // supersecret123Common Mistake
Committing your `.env` file to GitHub. Anyone could steal your passwords!
Best Practice
ALWAYS add `.env` to your `.gitignore` file immediately after creating a project.
Interview Tip
How do you securely handle production database credentials? (Answer: using environment variables instead of hardcoding).
Frequently Asked Questions
Is Node.js Frontend or Backend?
Node.js is purely for the Backend. It runs on the server, handling databases, APIs, and business logic.
What is npm?
NPM stands for Node Package Manager. It is the world's largest software registry, allowing you to download external libraries (like Express or Mongoose).