Answer: Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a web browser, often used for building scalable server-side applications.
// Basic Node.js server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Answer: JavaScript in the browser is used for client-side tasks such as DOM manipulation, while Node.js is used for server-side programming, file handling, networking, and more.
Answer: Modules are reusable blocks of code in Node.js, and can be built-in (like fs and http), third-party, or user-defined.
// Importing a built-in module
const fs = require('fs');
Answer: npm (Node Package Manager) is the default package manager for Node.js, used to install, update, and manage dependencies in Node.js projects.
npm install express
package.json and why is it important?Answer: package.json is the configuration file for a Node.js project, which holds metadata about the project and manages its dependencies.
Answer: Node.js follows an event-driven architecture where asynchronous operations are handled using events and callbacks.
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('event', () => {
console.log('Event triggered!');
});
emitter.emit('event');
EventEmitter in Node.js?Answer: The EventEmitter class is a core module that facilitates communication through events in Node.js applications.
Answer: Streams are objects in Node.js that allow reading and writing data in chunks rather than buffering it all in memory. They are useful for handling large files.
const fs = require('fs');
const readStream = fs.createReadStream('file.txt');
readStream.on('data', (chunk) => {
console.log(chunk.toString());
});
fs module in Node.js.Answer: The fs module provides methods for interacting with the file system, such as reading and writing files.
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Answer: Middleware is a function that has access to the request object (req), response object (res), and the next middleware function in the request-response cycle.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Middleware executed');
next();
});
require() and import in Node.js?Answer: require() is the CommonJS module system used in Node.js, while import is used in ES6 module syntax, which is more modern and has stricter loading behavior.
Answer: Node.js handles concurrency using an event loop and non-blocking I/O operations, allowing it to handle many requests at once without multi-threading.
Answer: The event loop is the mechanism that allows Node.js to perform non-blocking, asynchronous operations by offloading tasks to the operating system.
Answer: A callback is a function passed as an argument to another function, which is executed after an asynchronous operation is completed.
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
process in Node.js?Answer: The process object in Node.js provides information about the current Node.js process, such as environment variables, and allows developers to interact with the system.
console.log(process.env);
Answer: process.nextTick() queues the callback to be invoked in the current phase of the event loop, whereas setImmediate() schedules it for the next iteration of the event loop.
Answer: The cluster module allows you to create child processes (workers) that share the same server port, enabling the handling of multiple requests in parallel.
const cluster = require('cluster');
const http = require('http');
if (cluster.isMaster) {
cluster.fork();
} else {
http
.createServer((req, res) => {
res.writeHead(200);
res.end('Handled by worker');
})
.listen(8000);
}
Answer: Buffers are used to handle binary data in Node.js, especially when dealing with streams and file operations.
const buffer = Buffer.from('Hello');
console.log(buffer.toString()); // Outputs: Hello
Answer: Error handling in Node.js is typically done by passing errors to callback functions or using try...catch blocks with promises or async/await.
fs.readFile('file.txt', (err, data) => {
if (err) {
console.error('Error reading file', err);
} else {
console.log(data.toString());
}
});
Answer: Promises represent the eventual completion (or failure) of an asynchronous operation and allow you to chain operations.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});
promise.then((result) => console.log(result)); // Outputs: Done!
Answer: async/await is syntactic sugar built on top of promises, making asynchronous code look synchronous and easier to read.
async function fetchData() {
const result = await fetch('https://api.example.com');
console.log(await result.json());
}
Answer: Synchronous methods block the execution of further code until they complete, while asynchronous methods allow other operations to run while waiting for the current one to finish.
// Synchronous
const data = fs.readFileSync('file.txt');
// Asynchronous
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
Answer: Express.js is a popular web application framework for Node.js that simplifies the process of building web servers and APIs.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(3000, () => console.log('Server is running on port 3000'));
Answer: Middleware in Express.js is a function that can modify the request or response, perform logging, handle errors, etc., and pass control to the next middleware.
app.use((req, res, next) => {
console.log('Middleware called');
next();
});
Answer: Some best practices include using HTTPS, validating input data, protecting against SQL injection, securing dependencies, and using tools like Helmet for HTTP headers security.
const helmet = require('helmet');
app.use(helmet());