Table of Contents#
- What is Node.js?
- Event - Driven Architecture
- Modules in Node.js
- Callbacks and Asynchronous Programming
- HTTP Server in Node.js
- Best Practices for Node.js Development
1. What is Node.js?#
Quiz Question#
Question: What is Node.js?
- A) A programming language
- B) A runtime environment
- C) A database management system
Answer: B) A runtime environment
Explanation#
Node.js is an open - source, cross - platform JavaScript runtime environment. It allows developers to run JavaScript code outside of a web browser. It uses an event - driven, non - blocking I/O model, which makes it lightweight and efficient, especially for building real - time applications.
Example Usage#
You can run a simple JavaScript file using Node.js. For example, create a file hello.js with the following content:
console.log('Hello, Node.js!');Then run it in the terminal with node hello.js.
Common Practice#
Node.js is commonly used for building server - side applications (APIs, web servers), command - line tools, and for handling data processing tasks.
2. Event - Driven Architecture#
Quiz Question#
Question: How does Node.js handle events?
- A) Synchronously
- B) Asynchronously
- C) Both synchronously and asynchronously
Answer: B) Asynchronously
Explanation#
Node.js has an event - driven architecture. It uses an event loop to handle events. When an event occurs (like a file read operation, an HTTP request), Node.js doesn't block the execution. Instead, it registers a callback function and continues with other tasks. When the event is completed (e.g., the file is read), the callback is executed.
Example Usage#
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
console.log('Reading file...');In this example, while the readFile operation is in progress (asynchronous), the console.log('Reading file...') statement is executed immediately.
Best Practice#
Use asynchronous operations wherever possible in Node.js to avoid blocking the event loop. This improves the performance and scalability of your application.
3. Modules in Node.js#
Quiz Question#
Question: What is the purpose of modules in Node.js?
- A) To group related code
- B) To create global variables
- C) To define classes
Answer: A) To group related code
Explanation#
Modules in Node.js are used to organize code. You can create your own modules (e.g., a module for database operations) or use built - in modules (like fs for file system operations, http for HTTP server/client). Each module has its own scope, and you can export and import functions, objects, etc.
Example Usage#
Creating a custom module:
Create a file math.js:
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};Using the custom module:
const math = require('./math.js');
console.log(math.add(5, 3));
console.log(math.subtract(5, 3));Common Practice#
Follow the convention of using a single export (either a function, an object, or a class) for simplicity in smaller modules. For more complex modules, you can export multiple functions/objects.
4. Callbacks and Asynchronous Programming#
Quiz Question#
Question: What is a callback function in Node.js?
- A) A function that is called before another function
- B) A function that is passed as an argument to another function and is executed later
- C) A function that is called recursively
Answer: B) A function that is passed as an argument to another function and is executed later
Explanation#
Callbacks are a fundamental part of asynchronous programming in Node.js. As mentioned earlier, when an asynchronous operation (like setTimeout, readFile) is performed, a callback function is provided. The callback is executed when the operation is completed.
Example Usage#
function greet(name, callback) {
setTimeout(() => {
const message = `Hello, ${name}!`;
callback(message);
}, 1000);
}
greet('John', (msg) => {
console.log(msg);
});Here, the greet function takes a name and a callback as arguments. After a one - second delay (simulating an asynchronous operation), the callback is called with the greeting message.
Best Practice#
Avoid callback hell (nested callbacks) by using techniques like Promises (introduced in ES6) or async/await (introduced in ES8). For example, converting the above greet function to use Promises:
function greet(name) {
return new Promise((resolve) => {
setTimeout(() => {
const message = `Hello, ${name}!`;
resolve(message);
}, 1000);
});
}
greet('John').then((msg) => {
console.log(msg);
});5. HTTP Server in Node.js#
Quiz Question#
Question: How do you create a basic HTTP server in Node.js?
- A) Use the
httpmodule - B) Use the
expressmodule - C) Use the
fsmodule
Answer: A) Use the http module
Explanation#
The built - in http module in Node.js can be used to create an HTTP server. It provides methods to handle incoming requests and send responses.
Example Usage#
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});This code creates a simple HTTP server that listens on port 3000 and responds with "Hello, World!" for every request.
Common Practice#
In real - world applications, you might use frameworks like Express.js (which is built on top of the http module) for more advanced routing, middleware support, etc.
6. Best Practices for Node.js Development#
- Error Handling: Always handle errors in callbacks. Use try - catch blocks when using Promises or async/await.
- Code Organization: Use modules to organize your code. Follow a consistent directory structure (e.g.,
srcfor source code,testfor test files). - Performance: Optimize your code. Avoid memory leaks (e.g., by properly closing file descriptors, database connections). Use profiling tools (like
node --prof) to identify performance bottlenecks.
Reference#
- Node.js Official Documentation
- "Node.js Design Patterns" by Mario Casciaro
- MDN Web Docs - Node.js