fbpx

Node.js Basics

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to use JavaScript for server-side scripting, enabling the development of scalable and high-performance web applications. Here are the basics of Node.js:

1. Installation:

  • Visit the official Node.js website (https://nodejs.org/) to download and install Node.js. The installation includes both Node.js and npm (Node Package Manager).

2. Hello World:

  • Create a simple “Hello World” program to verify that Node.js is installed correctly. Create a file (e.g., app.js) and write the following code:
    javascript console.log("Hello, Node.js!");
  • Run the program in the terminal:
    bash node app.js

3. npm (Node Package Manager):

  • npm is the package manager for Node.js, used for installing and managing packages (libraries). Common npm commands include:
    • npm init: Initializes a new project and creates a package.json file.
    • npm install <package-name>: Installs a package locally.
    • npm install -g <package-name>: Installs a package globally.

4. Creating a Simple Web Server:

  • Node.js allows you to create a basic web server with just a few lines of code. Create a file (e.g., server.js) and use the following code: const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, Node.js Server!'); }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });
  • Run the server:
    bash node server.js
  • Access the server in a web browser at http://localhost:3000/.

5. Modules:

  • Node.js uses a module system to organize code. Core modules, such as http in the previous example, are included with Node.js. You can create your own modules and use them in your applications.

6. File System (fs) Module:

  • Node.js provides the fs module for file system operations. For example, reading a file: const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });

7. Asynchronous Programming:

  • Node.js is designed to be non-blocking and asynchronous. Many operations, such as file reading and HTTP requests, are performed asynchronously using callbacks or Promises.

8. Event Emitters:

  • Node.js uses an event-driven architecture. The events module allows you to create and handle custom events. For example: const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('Event occurred!'); }); myEmitter.emit('event');

9. Express.js (Web Framework):

  • Express.js is a popular web application framework for Node.js. It simplifies the process of building robust and scalable web applications. Install Express using npm:
    bash npm install express
  • Example of a simple Express app: const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, Express!'); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });

10. Middleware:

  • Express uses middleware functions to perform tasks during the request-response cycle. Middleware functions have access to the request and response objects and can modify them. Example: const express = require('express'); const app = express(); // Middleware function const logger = (req, res, next) => { console.log(`Request received at ${new Date()}`); next(); // Call the next middleware in the chain }; app.use(logger); app.get('/', (req, res) => { res.send('Hello, Express with Middleware!'); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`); });

These are the fundamental concepts and examples to get you started with Node.js. As you explore further, you’ll encounter additional features, frameworks, and best practices for building scalable and efficient server-side applications using Node.js.