Nodejs Questions


Beginners To Experts


The site is under development.

Nodejs Questions

In Node.js, `require()` is the older CommonJS module system and is synchronous. `import` is part of the ES Modules (ESM) system and is asynchronous.
- Use `require()` in CommonJS environments (default in Node.js before v12).
- Use `import` when using ES Modules (must use `.mjs` extension or set `"type": "module"` in `package.json`).
Example:
const fs = require('fs'); ← CommonJS
import fs from 'fs'; ← ES Module

The `package.json` file is the metadata file for a Node.js project. It includes project information like name, version, dependencies, scripts, author, license, and more.
- It allows easy sharing and installation of packages using `npm install`.
- It enables running scripts using commands like `npm start`, `npm test`, etc.
Example:
{ "name": "my-app", "version": "1.0.0", "scripts": { "start": "node app.js" }, "dependencies": { "express": "^4.17.1" } }

Node.js is single-threaded and uses an event-driven architecture. The event loop is a mechanism that handles asynchronous operations like I/O, timers, and callbacks.
It has phases like: - Timers
- Pending Callbacks
- Idle/Prepare
- Poll
- Check
- Close callbacks

The loop runs continuously, offloading I/O tasks and executing callbacks in a non-blocking manner.

- `process.nextTick()` queues a callback to run **before** the next event loop tick.
- `setImmediate()` queues a callback to run **on the next loop iteration**, after I/O events.
- `setTimeout()` schedules a task after a given delay (minimum delay of 1ms).

Order of execution (typically):
`process.nextTick()` → `Promise.then()` → `setTimeout()`/`setImmediate()` depending on context.

Use `nextTick()` for critical, immediate tasks (can starve the event loop). Use `setImmediate()` for deferring.

The `fs` (File System) module allows Node.js to interact with the file system.
It provides both **synchronous** and **asynchronous** methods to read, write, delete, and modify files and directories.

Example:
const fs = require('fs');
// Asynchronous read
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

// Synchronous write
fs.writeFileSync('output.txt', 'Hello World');

Middleware in Express.js are functions that execute during the request-response cycle.
They have access to the `req`, `res`, and `next` objects.
Middleware can:
- Modify request and response objects
- End the request-response cycle
- Call the next middleware

Example:
const express = require('express');
const app = express();

// Custom middleware
app.use((req, res, next) => {
console.log('Request received');
next();
});

app.get('/', (req, res) => {
res.send('Hello World');
});

app.listen(3000);

In Express.js, you handle errors using **error-handling middleware**, defined with four arguments: `(err, req, res, next)`.

Example:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
throw new Error('Something went wrong');
});

// Error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});

app.listen(3000);

The `require()` function is used to import modules, JSON, and local files in Node.js.
It executes the file once and caches the result for future use.

Example:
// Import core module
const fs = require('fs');

// Import local module
const myUtils = require('./utils');

// Import JSON
const config = require('./config.json');

- `module.exports` is the actual object returned by `require()`.
- `exports` is a reference to `module.exports` by default.

You should use **only one** to export your module properly. If you assign a new object to `exports`, it breaks the reference.

Example:
// Correct
module.exports = function() { return 'Hello'; };

// OR

exports.sayHi = function() { return 'Hi'; };

// Incorrect
exports = function() {}; // Breaks reference to module.exports

Environment variables are accessed in Node.js using `process.env`.
They store sensitive info like API keys, database URLs, and secrets.

Example:
// .env file
PORT=3000
API_KEY=abcdefg123

// app.js
require('dotenv').config();
const port = process.env.PORT;
const key = process.env.API_KEY;

console.log(`Running on port ${port} with key ${key}`);


Make sure to use the `dotenv` package to load variables from `.env`.

To serve static files like images, CSS, or JavaScript in Express.js, use `express.static`.
Files will be accessible from the specified directory.

Example:
const express = require('express');
const app = express();

// Serve static files from 'public' folder
app.use(express.static('public'));

app.listen(3000);


Now visiting `http://localhost:3000/logo.png` will serve `public/logo.png`.

`next()` is used to pass control to the next middleware function in the stack.
Without it, the request will hang and not continue.

Example:
app.use((req, res, next) => {
console.log('Step 1');
next();
});

app.use((req, res, next) => {
console.log('Step 2');
res.send('Done');
});

Streams are used to handle reading or writing data piece by piece, especially for large files.
Node.js has four types: Readable, Writable, Duplex, and Transform.

Example of reading a file as a stream:
const fs = require('fs');
const readStream = fs.createReadStream('large.txt');

readStream.on('data', chunk => {
console.log('Chunk received:', chunk);
});

A REST API defines endpoints that allow CRUD operations over HTTP using Express.js.
Example:
const express = require('express');
const app = express();
app.use(express.json());

let items = [];

// GET
app.get('/items', (req, res) => {
res.json(items);
});

// POST
app.post('/items', (req, res) => {
items.push(req.body);
res.send('Item added');
});

app.listen(3000);

A callback is a function passed as an argument to another function and executed later.
It is commonly used for asynchronous operations in Node.js.

Example:
const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});

This example demonstrates how to read a file asynchronously in Node.js using the built-in fs module.

<!-- Example: Read a file asynchronously using fs -->
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File contents:', data);
});
File contents: Hello, this is a sample file content!

This example shows how to write data to a file synchronously in Node.js using fs.

<!-- Example: Write file synchronously using fs -->
const fs = require('fs');
try {
fs.writeFileSync('output.txt', 'This is synchronous write example.');
console.log('File written successfully.');
} catch (err) {
console.error('Error writing file:', err);
}
File written successfully.

This example creates a basic HTTP server that responds with "Hello World" for all requests.

<!-- Example: Simple HTTP server -->
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Server running at http://localhost:3000/

This example shows how to create and listen to custom events using the EventEmitter class.

<!-- Example: EventEmitter usage -->
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('greet', () => {
console.log('Hello event triggered!');
});
myEmitter.emit('greet');
Hello event triggered!

This example demonstrates creating a Promise that resolves after 2 seconds.

<!-- Example: Promise usage -->
const waitTwoSeconds = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Done waiting 2 seconds');
}, 2000);
});
};
waitTwoSeconds().then(message => {
console.log(message);
});
Done waiting 2 seconds

This example shows async/await syntax to handle asynchronous operations more readably.

<!-- Example: Async/Await usage -->
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function asyncExample() {
console.log('Waiting 1 second...');
await wait(1000);
console.log('Done!');
}
asyncExample();
Waiting 1 second...
Done!

This example shows how to create a simple Express server responding with "Hello from Express".

<!-- Example: Simple Express server -->
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express');
});
app.listen(3000, () => {
console.log('Express server running on http://localhost:3000');
});
Express server running on http://localhost:3000

This example demonstrates how to use middleware in Express to log each request.

<!-- Example: Express middleware -->
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello Middleware');
});
app.listen(3000, () => {
console.log('Server running with middleware on http://localhost:3000');
});
Server running with middleware on http://localhost:3000
GET /

This example shows how to parse JSON request bodies in Express using built-in middleware.

<!-- Example: Express JSON parsing -->
const express = require('express');
const app = express();
app.use(express.json());
app.post('/data', (req, res) => {
console.log('Received JSON:', req.body);
res.send('JSON received');
});
app.listen(3000, () => {
console.log('Server listening for JSON on http://localhost:3000');
});
Server listening for JSON on http://localhost:3000
Received JSON: {"key":"value"}

This example shows how to use the dotenv package to load environment variables from a .env file.

<!-- Example: Using dotenv for env variables -->
require('dotenv').config();
console.log('Your API key is:', process.env.API_KEY);
Your API key is: 12345-ABCDE

This example shows how to serve static files like images, CSS, and JS from a folder named 'public'.

<!-- Example: Serve static files with Express -->
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Static files served on http://localhost:3000');
});
Static files served on http://localhost:3000

This example illustrates how to read query parameters from a URL in Express.

<!-- Example: Query parameters in Express -->
const express = require('express');
const app = express();
app.get('/search', (req, res) => {
const term = req.query.term;
res.send(`You searched for: ${term}`);
});
app.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});
Server listening on http://localhost:3000
Example: You searched for: nodejs

This example demonstrates extracting dynamic parameters from the URL path.

<!-- Example: URL parameters in Express -->
const express = require('express');
const app = express();
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID requested: ${userId}`);
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Server running on http://localhost:3000
Example: User ID requested: 123

This example shows setting up multiple routes responding with different messages.

<!-- Example: Basic routes in Express -->
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Server running at http://localhost:3000
Example responses:
/ → Home Page
/about → About Page

This explains how to use Nodemon to automatically restart your Node.js server when files change.

<!-- Usage: Run your app with nodemon -->
npm install -g nodemon
nodemon app.js

/* This will watch your files and restart the server when changes occur. */
[nodemon] starting `node app.js`
Server running on http://localhost:3000
[nodemon] restarting due to changes...

This example shows how to use the dotenv package to load environment variables from a .env file.

<!-- Example: Using dotenv -->
npm install dotenv

/* .env file content:
PORT=4000
*/

const express = require('express');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Server running with dotenv');
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Server running on port 4000

This example demonstrates how to connect to a MongoDB database using Mongoose, an ODM for MongoDB in Node.js.

<!-- Example: Connect to MongoDB with Mongoose -->
const mongoose = require('mongoose');
const uri = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch(err => {
console.error('MongoDB connection error:', err);
});
Connected to MongoDB

This example shows how to define a schema and model using Mongoose for MongoDB collections.

<!-- Example: Define Mongoose Schema and Model -->
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);

// Create a new user instance
const user = new User({ name: 'Alice', email: 'alice@example.com', age: 30 });
user.save()
.then(() => console.log('User saved'))
.catch(err => console.error('Save error:', err));
User saved

This example shows basic Create, Read, Update, Delete operations using Mongoose.

<!-- Example: Basic CRUD with Mongoose -->
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);

// Create
const newUser = new User({ name: 'Bob' });
newUser.save()
.then(() => console.log('User created'))
.catch(console.error);

// Read
User.find({ name: 'Bob' })
.then(users => console.log('Found users:', users))
.catch(console.error);

// Update
User.updateOne({ name: 'Bob' }, { name: 'Robert' })
.then(() => console.log('User updated'))
.catch(console.error);

// Delete
User.deleteOne({ name: 'Robert' })
.then(() => console.log('User deleted'))
.catch(console.error);
User created
Found users: [...]
User updated
User deleted

Middleware functions execute during the request-response cycle. Here is how to write a simple logger middleware.

<!-- Example: Middleware logger in Express -->
const express = require('express');
const app = express();

// Logger middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Continue to next middleware or route handler
});

app.get('/', (req, res) => {
res.send('Hello from Express with middleware!');
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Server running on http://localhost:3000
GET /

body-parser middleware parses incoming request bodies in middleware before your handlers.

<!-- Example: Use body-parser in Express -->
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// parse application/json
app.use(bodyParser.json());

app.post('/data', (req, res) => {
console.log(req.body);
res.send('Data received');
});

app.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});
Server listening on http://localhost:3000
Example POST /data with JSON body logs the parsed data.

This example shows a basic error handling middleware in Express.

<!-- Example: Error handling middleware -->
const express = require('express');
const app = express();

app.get('/', (req, res) => {
throw new Error('Something went wrong!');
});

// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send('Internal Server Error');
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Server running on http://localhost:3000
Accessing / triggers error and returns 500 Internal Server Error

This example demonstrates how to use Express Router to split routes into modular files.

<!-- Example: Express Router -->
const express = require('express');
const app = express();
const router = express.Router();

router.get('/info', (req, res) => {
res.send('Info Page from Router');
});

app.use('/api', router);

app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Server running at http://localhost:3000
Access /api/info to see 'Info Page from Router'

This example explains how to implement session management with express-session.

<!-- Example: express-session -->
const express = require('express');
const session = require('express-session');
const app = express();

app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));

app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`Number of views: ${req.session.views}`);
} else {
req.session.views = 1;
res.send('Welcome! Refresh page to track views.');
}
});

app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
Welcome! Refresh page to track views.
Number of views: 2
Number of views: 3
...

This example shows how to call OpenAI's GPT API to get text completions from Node.js.

<!-- Example: OpenAI API Completion Call -->
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
});
const openai = new OpenAIApi(configuration);

async function getCompletion() {
const response = await openai.createCompletion({
model: 'text-davinci-003',
prompt: 'Write a short poem about Node.js',
max_tokens: 50
});
console.log(response.data.choices[0].text.trim());
}

getCompletion();
Node.js, swift and bright,
Server-side in the night,
JavaScript's true delight.

This example creates a simple Express API route that returns a ChatGPT completion.

<!-- Example: Express + OpenAI Chat Completion -->
const express = require('express');
const { Configuration, OpenAIApi } = require('openai');
const app = express();

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
});
const openai = new OpenAIApi(configuration);

app.get('/chat', async (req, res) => {
try {
const completion = await openai.createChatCompletion({
model: 'gpt-4o-mini',
messages: [
{ role: 'user', content: 'Hello, ChatGPT!' }
]
});
res.send(completion.data.choices[0].message.content);
} catch (error) {
res.status(500).send('Error from OpenAI API');
}
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Hello! How can I assist you today?

This example shows a simple linear regression prediction using TensorFlow.js in Node.js.

<!-- Example: TensorFlow.js Linear Regression -->
const tf = require('@tensorflow/tfjs-node');

async function run() {
// Training data
const xs = tf.tensor1d([1, 2, 3, 4]);
const ys = tf.tensor1d([1, 3, 5, 7]);

// Define a simple linear model y = ax + b
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });

// Train the model
await model.fit(xs, ys, { epochs: 100 });

// Predict y for x=5
const output = model.predict(tf.tensor1d([5]));
output.print();
}

run();
Tensor
[[9.999999]]

This example streams AI-generated text back to the client using SSE and OpenAI's streaming API.

<!-- Example: SSE streaming with Express + OpenAI -->
const express = require('express');
const { Configuration, OpenAIApi } = require('openai');
const app = express();

const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY });
const openai = new OpenAIApi(configuration);

app.get('/stream', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();

const completion = await openai.createChatCompletion({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Stream a short story about Node.js' }],
stream: true
}, { responseType: 'stream' });

completion.data.on('data', data => {
const lines = data.toString().split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
const message = line.replace(/^data: /, '');
if (message === '[DONE]') {
res.end();
return;
}
try {
const parsed = JSON.parse(message);
const text = parsed.choices[0].delta.content;
if (text) {
res.write(`data: ${text}\n\n`);
}
} catch (error) {
console.error('Could not JSON parse stream message', message, error);
}
}
});
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
data: Once upon a time in a Node.js world...
data: streams flowed smoothly,
data: and developers were happy.

Multer helps handle multipart/form-data to upload files in Express.

<!-- Example: File upload using Multer -->
const express = require('express');
const multer = require('multer');
const app = express();

const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded: ${req.file.originalname}`);
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
File uploaded: example.png

This example sets up a simple WebSocket chat server using Socket.io.

<!-- Example: Socket.io Chat Server -->
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on('connection', (socket) => {
console.log('User connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});

server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
User connected
User disconnected

This example demonstrates a simple REST API to create and get users using MongoDB and Mongoose.

<!-- Example: Express + Mongoose REST API -->
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/testdb');

const userSchema = new mongoose.Schema({ name: String, email: String });
const User = mongoose.model('User', userSchema);

app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
});

app.get('/users', async (req, res) => {
const users = await User.find();
res.send(users);
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
POST /users => { "_id": "...", "name": "John", "email": "john@example.com" }
GET /users => [ { "_id": "...", "name": "John", "email": "john@example.com" } ]

This example uses TensorFlow.js MobileNet model to predict image captions in Node.js.

<!-- Example: Image Captioning with TensorFlow.js -->
const tf = require('@tensorflow/tfjs-node');
const mobilenet = require('@tensorflow-models/mobilenet');
const fs = require('fs');
const jpeg = require('jpeg-js');

function readImage(path) {
const buf = fs.readFileSync(path);
const pixels = jpeg.decode(buf, true);
return tf.browser.fromPixels({ data: pixels.data, width: pixels.width, height: pixels.height });
}

async function classifyImage() {
const image = readImage('./image.jpg');
const model = await mobilenet.load();
const predictions = await model.classify(image);
console.log('Predictions:', predictions);
}

classifyImage();
Predictions: [ { className: 'coffee mug', probability: 0.85 }, { className: 'cup', probability: 0.1 } ]

This example shows how to secure routes using JSON Web Tokens (JWT).

<!-- JWT Authentication Middleware Example -->
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());

const secret = 'mysecretkey';

// Middleware to verify JWT token
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);

jwt.verify(token, secret, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}

// Login route issues JWT
app.post('/login', (req, res) => {
// Normally check user credentials here
const username = req.body.username;
const user = { name: username };
const accessToken = jwt.sign(user, secret, { expiresIn: '1h' });
res.json({ accessToken });
});

// Protected route
app.get('/protected', authenticateToken, (req, res) => {
res.send(`Hello ${req.user.name}, you have accessed a protected route!`);
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
POST /login { "username": "Alice" }
→ { "accessToken": "eyJhbGciOiJIUzI1NiIsIn..." }
GET /protected with Bearer token
→ Hello Alice, you have accessed a protected route!

This example uses express-rate-limit middleware to limit API request rates.

<!-- Rate Limiting with express-rate-limit -->
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();

// Limit to 5 requests per minute per IP
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 5,
message: 'Too many requests, please try again later.'
});

// Apply to all requests
app.use(limiter);

app.get('/', (req, res) => {
res.send('Welcome to the rate-limited API!');
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
1st to 5th request → Welcome to the rate-limited API!
6th request → Too many requests, please try again later.

Use Sharp to resize uploaded images in Express apps.

<!-- Upload and Resize Image with Multer & Sharp -->
const express = require('express');
const multer = require('multer');
const sharp = require('sharp');
const fs = require('fs');
const app = express();

const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('image'), async (req, res) => {
const inputPath = req.file.path;
const outputPath = `resized-${req.file.originalname}`;
await sharp(inputPath)
.resize(200, 200)
.toFile(outputPath);
fs.unlinkSync(inputPath); // delete original
res.send(`Image resized and saved as ${outputPath}`);
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Image resized and saved as resized-example.jpg

Simple example calling OpenAI's ChatGPT from Express.

<!-- OpenAI ChatGPT Integration -->
const express = require('express');
const { Configuration, OpenAIApi } = require('openai');
const app = express();
app.use(express.json());

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

app.post('/chat', async (req, res) => {
const userMessage = req.body.message;
const completion = await openai.createChatCompletion({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: userMessage }],
});
res.json({ reply: completion.data.choices[0].message.content });
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
POST /chat { "message": "Hello AI!" }
→ { "reply": "Hello! How can I assist you today?" }

This example shows how to generate text embeddings with OpenAI and perform a simple similarity search.

<!-- OpenAI Embeddings for Text Search -->
const { Configuration, OpenAIApi } = require('openai');
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const documents = [
"Node.js is a JavaScript runtime.",
"Express is a web framework for Node.js.",
"OpenAI provides powerful AI APIs."
];

async function embed(text) {
const response = await openai.createEmbedding({
model: 'text-embedding-3-small',
input: text
});
return response.data.data[0].embedding;
}

function cosineSimilarity(vecA, vecB) {
const dotProduct = vecA.reduce((sum, a, i) => sum + a * vecB[i], 0);
const magA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));
const magB = Math.sqrt(vecB.reduce((sum, b) => sum + b * b, 0));
return dotProduct / (magA * magB);
}

async function search(query) {
const queryEmbedding = await embed(query);
const scores = await Promise.all(documents.map(async (doc) => {
const docEmbedding = await embed(doc);
return { doc, score: cosineSimilarity(queryEmbedding, docEmbedding) };
}));
scores.sort((a, b) => b.score - a.score);
return scores[0];
}

search("web framework").then(result => {
console.log("Best match:", result.doc);
});
Best match: Express is a web framework for Node.js.

This example demonstrates connecting to MongoDB and performing CRUD with Mongoose.

<!-- MongoDB Mongoose Example -->
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');

const userSchema = new mongoose.Schema({
name: String,
age: Number
});

const User = mongoose.model('User', userSchema);

// Create and save a user
async function createUser() {
const user = new User({ name: 'Bob', age: 25 });
await user.save();
console.log('User saved:', user);
}

createUser();
User saved: { _id: '...', name: 'Bob', age: 25, __v: 0 }

Example shows how to cache a value in Redis with Node.js.

<!-- Redis Cache Example -->
const redis = require('redis');
const client = redis.createClient();
client.connect();

async function cacheExample() {
await client.set('myKey', 'some cached value', { EX: 10 }); // expires in 10 seconds
const value = await client.get('myKey');
console.log('Cached value:', value);
}

cacheExample();
Cached value: some cached value

Simple WebSocket server echoing messages back to clients.

<!-- WebSocket Server with ws -->
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('Received:', message);
ws.send(`Echo: ${message}`);
});
ws.send('Welcome to the WebSocket server!');
});

console.log('WebSocket server running on ws://localhost:8080');
Client connects:
→ Welcome to the WebSocket server!
Client sends "Hello"
→ Echo: Hello

How to load environment variables from a .env file using dotenv.

<!-- dotenv usage example -->
require('dotenv').config();
console.log('DB_HOST:', process.env.DB_HOST);
DB_HOST: localhost

Schedule a task to run every minute using node-cron.

<!-- node-cron example -->
const cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('Task runs every minute:', new Date().toLocaleTimeString());
});
Task runs every minute: 12:00:00 PM
Task runs every minute: 12:01:00 PM
...

Passport.js local strategy example for basic user authentication in Express.

<!-- Passport.js local auth example -->
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const app = express();

app.use(express.urlencoded({ extended: false }));
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Define local strategy
passport.use(new LocalStrategy((username, password, done) => {
if (username === 'user' && password === 'pass') {
return done(null, { id: 1, username });
} else {
return done(null, false);
}
}));

// Serialize user to session
passport.serializeUser((user, done) => done(null, user.id));

// Deserialize user from session
passport.deserializeUser((id, done) => {
done(null, { id, username: 'user' });
});

// Login route
app.post('/login', passport.authenticate('local', {
successRedirect: '/success',
failureRedirect: '/login'
}));

// Success route
app.get('/success', (req, res) => {
res.send('Logged in! Welcome ' + req.user.username);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
POST /login with username=user and password=pass
→ Redirect to /success
/success page shows:
Logged in! Welcome user

Use cluster module to fork multiple worker processes for handling requests concurrently.

<!-- Node.js cluster example -->
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers share the TCP connection
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from worker ' + process.pid);
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
Master 12345 is running
Worker 12346 started
Worker 12347 started
...
Client request returns:
Hello from worker 12346

Use fs/promises to read and write files asynchronously with async/await.

<!-- fs/promises example -->
const fs = require('fs').promises;

async function fileOps() {
await fs.writeFile('test.txt', 'Hello, Node.js!');
const content = await fs.readFile('test.txt', 'utf-8');
console.log('File content:', content);
}

fileOps();
File content: Hello, Node.js!

Create and listen to custom events using EventEmitter class.

<!-- EventEmitter example -->
const EventEmitter = require('events');
const emitter = new EventEmitter();

// Listen for custom event
emitter.on('greet', (name) => {
console.log('Hello, ' + name);
});

// Emit the event
emitter.emit('greet', 'Alice');
Hello, Alice

Basic HTTP server responding to all requests with "Hello World".

<!-- http server example -->
const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Access http://localhost:3000/
Response:
Hello World

Use readable and writable streams to process large files efficiently without loading them entirely into memory.

<!-- Stream example: Copy a file using streams -->
const fs = require('fs');

// Create readable stream from source file
const readable = fs.createReadStream('source.txt');

// Create writable stream to destination file
const writable = fs.createWriteStream('destination.txt');

// Pipe readable stream into writable stream
readable.pipe(writable);

console.log('File copy started using streams');
File copy started using streams
// destination.txt is created as a copy of source.txt asynchronously

Middleware functions are functions that have access to the request and response objects and can modify them or control request flow.

<!-- Express middleware example -->
const express = require('express');
const app = express();

// Middleware to log request method and URL
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // pass control to the next handler
});

app.get('/', (req, res) => {
res.send('Hello from Express with middleware');
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
GET /
Response: Hello from Express with middleware

Use dotenv package to load environment variables from a .env file into process.env.

<!-- Using dotenv example -->
require('dotenv').config();

console.log('Your API key is:', process.env.API_KEY);

// Create a .env file with:
// API_KEY=123456789
Your API key is: 123456789

Basic REST API example with Express handling GET and POST requests.

<!-- Basic REST API example -->
const express = require('express');
const app = express();
app.use(express.json());

let items = [{ id: 1, name: 'Item 1' }];

// GET all items
app.get('/items', (req, res) => {
res.json(items);
});

// POST new item
app.post('/items', (req, res) => {
const newItem = { id: items.length + 1, name: req.body.name };
items.push(newItem);
res.status(201).json(newItem);
});

app.listen(3000, () => console.log('REST API running on port 3000'));
GET /items
Response: [{ "id": 1, "name": "Item 1" }]
POST /items with { "name": "Item 2" }
Response: { "id": 2, "name": "Item 2" }

Send emails programmatically using Nodemailer SMTP transport.

<!-- Nodemailer example -->
const nodemailer = require('nodemailer');

async function sendMail() {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your.email@gmail.com',
pass: 'yourpassword'
}
});

let info = await transporter.sendMail({
from: '"Node.js" <your.email@gmail.com>',
to: 'friend@example.com',
subject: 'Hello ✔',
text: 'Hello world?',
});

console.log('Message sent: %s', info.messageId);
}

sendMail().catch(console.error);
Message sent: <unique-message-id>

Use Node.js built-in debugger for step-by-step code inspection.

<!-- Debug example -->
function add(a, b) {
debugger; // Execution will pause here if debugger is attached
return a + b;
}

console.log(add(2, 3));

// Run with:
// node inspect yourfile.js
5
// Execution pauses at debugger line when run with node inspect

The cluster module helps create child processes (workers) to utilize all CPU cores.

<!-- Cluster example to fork workers -->
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}

cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers can share the same server
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from worker ' + process.pid);
}).listen(8000);

console.log(`Worker ${process.pid} started`);
}
Master 12345 is running
Worker 12346 started
Worker 12347 started
...
// Server listens on port 8000 with workers handling requests

Use multer middleware to handle multipart/form-data for file uploads in Express.

<!-- Express file upload example -->
const express = require('express');
const multer = require('multer');
const app = express();

// Set storage destination and filename
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});

const upload = multer({ storage: storage });

// Upload single file with field name 'myfile'
app.post('/upload', upload.single('myfile'), (req, res) => {
res.send('File uploaded: ' + req.file.filename);
});

app.listen(3000, () => console.log('Server started on port 3000'));
POST /upload with form-data containing 'myfile'
Response: File uploaded: 1684541234567-filename.jpg

Async/await makes asynchronous code look synchronous and easier to read.

<!-- Async/Await example -->
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function main() {
console.log('Start');
await wait(2000); // wait for 2 seconds
console.log('End after 2 seconds');
}

main();
Start
(waits 2 seconds)
End after 2 seconds

EventEmitter allows creation and handling of custom events for async communication.

<!-- EventEmitter example -->
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

// Listen for 'greet' event
myEmitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});

// Emit 'greet' event
myEmitter.emit('greet', 'Alice');
Hello, Alice!

The ws library provides WebSocket server and client for real-time, full-duplex communication.

<!-- WebSocket server example using ws -->
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('Received:', message);
ws.send('Hello client! You sent: ' + message);
});
ws.send('Welcome to the WebSocket server!');
});
Client connects → "Welcome to the WebSocket server!"
Client sends "Hi" → Server logs "Received: Hi"
Server replies "Hello client! You sent: Hi"

child_process module allows running shell commands or scripts asynchronously.

<!-- Run external command example -->
const { exec } = require('child_process');

exec('ls -l', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
stdout: (list of files in current directory)
stderr: (empty if no error)

Use crypto module to securely hash passwords with algorithms like SHA-256.

<!-- Hash password example -->
const crypto = require('crypto');

function hashPassword(password) {
return crypto.createHash('sha256')
.update(password)
.digest('hex');
}

const hashed = hashPassword('mysecretpassword');
console.log('Hashed password:', hashed);
Hashed password: e7cf3ef4f17c3999a94f2c6f612e8a888e5... (64 hex chars)