Comprehensive Node.js development skill covering event loop, async patterns, streams, file system, HTTP servers, process management, and modern Node.js best practices
A comprehensive skill for building modern Node.js applications covering backend APIs, CLI tools, microservices, and real-time applications.
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that enables server-side JavaScript execution. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient for building scalable network applications.
This skill provides comprehensive guidance on:
Node.js excels at:
macOS/Linux (nvm):
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Install Node.js LTS
nvm install --lts
# Use specific version
nvm use 18
# Set default version
nvm alias default 18
Windows (nvm-windows):
# Download installer from: https://github.com/coreybutler/nvm-windows/releases
# Then install Node.js
nvm install lts
nvm use lts
node --version
npm --version
Create a file hello.js:
console.log('Hello, Node.js!');
Run it:
node hello.js
# Create project directory
mkdir my-nodejs-app
cd my-nodejs-app
# Initialize package.json
npm init -y
# Install dependencies
npm install express
# Create main file
touch index.js
// index.js
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Run the server:
node index.js
Visit http://localhost:3000 in your browser.
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
The event loop is what allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded. It's the mechanism that handles asynchronous callbacks.
Key Points:
Node.js uses non-blocking I/O calls, allowing it to support thousands of concurrent connections without the overhead of thread management.
// Blocking (synchronous)
const data = fs.readFileSync('file.txt'); // Waits for file read
console.log(data);
// Non-blocking (asynchronous)
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('This executes immediately');
Node.js uses modules to organize code into reusable components. It supports both CommonJS (traditional) and ES Modules (modern).
CommonJS:
// Export
module.exports = { add, subtract };
// Import
const math = require('./math');
ES Modules:
// Export
export { add, subtract };
// Import
import { add, subtract } from './math.js';
NPM is the world's largest software registry. It allows you to install, share, and manage dependencies.
# Install package
npm install express
# Install as dev dependency
npm install --save-dev jest
# Install globally
npm install -g nodemon
# Uninstall package
npm uninstall express
# Update packages
npm update
# List installed packages
npm list
# Check for outdated packages
npm outdated
Build RESTful APIs with Express.js:
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/users', (req, res) => {
res.json({ users: [] });
});
app.post('/api/users', (req, res) => {
const user = req.body;
res.status(201).json(user);
});
app.listen(3000);
Use WebSockets for real-time communication:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
// Broadcast to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
Create command-line tools:
#!/usr/bin/env node
const args = process.argv.slice(2);
const command = args[0];
switch (command) {
case 'help':
console.log('Available commands: help, version');
break;
case 'version':
console.log('v1.0.0');
break;
default:
console.log('Unknown command');
}
Process files efficiently with streams:
const fs = require('fs');
const readStream = fs.createReadStream('large-file.txt');
const writeStream = fs.createWriteStream('output.txt');
readStream.pipe(writeStream);
writeStream.on('finish', () => {
console.log('File processing complete');
});
A typical Node.js project structure:
my-app/
├── node_modules/ # Dependencies
├── src/ # Source code
│ ├── controllers/ # Route handlers
│ ├── models/ # Data models
│ ├── routes/ # API routes
│ ├── middleware/ # Custom middleware
│ ├── utils/ # Utility functions
│ └── config/ # Configuration files
├── tests/ # Test files
├── public/ # Static files
├── .env # Environment variables (not committed)
├── .gitignore # Git ignore file
├── package.json # Project metadata and dependencies
├── package-lock.json # Locked dependency versions
└── index.js # Entry point
Use environment variables for configuration:
.env file:
PORT=3000
NODE_ENV=development
DATABASE_URL=mongodb://localhost/myapp
JWT_SECRET=your-secret-key
Load with dotenv:
require('dotenv').config();
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
nodemon - Auto-restart on file changes
npm install -g nodemon
nodemon index.js
ESLint - Code linting
npm install --save-dev eslint
npx eslint --init
Prettier - Code formatting
npm install --save-dev prettier
npx prettier --write .
Jest - Testing framework
npm install --save-dev jest
npm test
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest",
"lint": "eslint .",
"format": "prettier --write ."
}
}
Run scripts:
npm start
npm run dev
npm test
Always handle errors properly:
// Async/await
try {
const data = await fetchData();
} catch (err) {
console.error('Error:', err);
}
// Promises
fetchData()
.then(data => process(data))
.catch(err => console.error('Error:', err));
// Process-level error handling
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
process.exit(1);
});
# Start with inspector
node --inspect index.js
# Debug from the start
node --inspect-brk index.js
Open chrome://inspect in Chrome to debug.
Create .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/index.js"
}
]
}
Press F5 to start debugging.
console.log('Variable:', variable);
console.error('Error:', error);
console.table(arrayOfObjects);
console.time('operation');
// ... code to measure
console.timeEnd('operation');
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// math.test.js
const { add } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
const request = require('supertest');
const app = require('./app');
describe('GET /api/users', () => {
it('responds with json', async () => {
const response = await request(app)
.get('/api/users')
.expect('Content-Type', /json/)
.expect(200);
});
});
Heroku
heroku create
git push heroku main
Vercel
npm install -g vercel
vercel
AWS (Elastic Beanstalk, Lambda)
Google Cloud Platform
DigitalOcean
Railway
Render
# Install PM2
npm install -g pm2
# Start application
pm2 start index.js
# Start with name
pm2 start index.js --name "my-app"
# Start in cluster mode
pm2 start index.js -i max
# Monitor
pm2 monit
# List processes
pm2 list
# Restart
pm2 restart my-app
# Stop
pm2 stop my-app
# View logs
pm2 logs
# Save process list
pm2 save
# Auto-start on boot
pm2 startup
This skill is provided as-is for educational and development purposes.
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer
Tags:nodejs, javascript, backend, async, streams, http, api, server