0% found this document useful (0 votes)
11 views

node1

Node.js is an open-source JavaScript runtime built on Chrome's V8 engine, enabling server-side execution of JavaScript for scalable applications. It removes browser-specific features, providing server-side modules for file handling, HTTP requests, and more. The document also covers setting up Node.js, using the fs module for file operations, and creating a basic HTTP server to handle requests and responses.

Uploaded by

xeroxxwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

node1

Node.js is an open-source JavaScript runtime built on Chrome's V8 engine, enabling server-side execution of JavaScript for scalable applications. It removes browser-specific features, providing server-side modules for file handling, HTTP requests, and more. The document also covers setting up Node.js, using the fs module for file operations, and creating a basic HTTP server to handle requests and responses.

Uploaded by

xeroxxwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Introduction to Node.

js
Behind every scalable application is a strong backend. Let's build one with Node.js!
What is Node.js

1. JavaScript Runtime: Node.js is an open-source, cross-platform runtime

environment for executing JavaScript code outside of a browser.

2. NodeJs is a JavaScript in a different-environment means Running JS on


the,server or any computer.
3. Built on Chrome's V8 Engine: It runs on the V8 engine, which compiles
JavaScript directly to native machine code, enhancing performance.

4. V8 is written in C++ for speed.

5. V8 + Backend Features = NodeJs


6. Full-Stack JavaScript: Allows using JavaScript on both server and client sides.
7. Scalability: Ideal for scalable network applications due to its architecture.
8. Versatility: Suitable for web, real-time chat, and REST API servers.
9. Server-Side Capabilities: Node.js enables JavaScript to run on the server,
handling HTTP requests, file operations, and other server-side functionalities.
10. Modules: Organize code into reusable modules using require().
what node js remove from v8?

Node.js is built on the V8 JavaScript engine, but it removes or replaces certain


browser-specific features that are not needed for server-side execution.
Things Node.js Removes from V8:

1⃣ DOM (Document Object Model) – No document, window, or alert since there's no browser.
2⃣ Web APIs – No fetch(), localStorage, sessionStorage, navigator, etc.
3⃣ Rendering Engine – No support for CSS, HTML, or Canvas.
4⃣ Security Restrictions – No Same-Origin Policy (CORS) since it's a backend environment.
5⃣ Event Loop Differences – Uses its own libuv-based event loop instead of the browser's.

Instead, Node.js provides server-side modules like fs (file system), http (server handling),
and os (system info) to interact with the machine directly. 🚀
JavaScript on the Client (Browser Side)

On the client side, JavaScript runs in the browser and is mainly used for:
JavaScript on the Client (Browser Side)

Displays Web Page: Turns HTML code into what you see on screen.

User Clicks: Helps you interact with the web page.

Updates Content: Allows changes to the page using JavaScript.

Loads Files: Gets HTML, images, etc., from the server.

Making API Calls – Fetching data from servers using fetch() or XMLHttpRequest.
Client-Side Validation – Checking user input before sending it to the server.
Animations & Effects – Creating smooth UI animations with libraries like GSAP or CSS
transitions.
JavaScript on the Server
When JavaScript runs on the server-side using Node.js, it is used for:

Handling HTTP Requests & Responses – Creating web servers with http or Express.js.

✅ Working with Databases – Connecting to MongoDB, MySQL, PostgreSQL, etc.

✅ Processing Business Logic – Performing calculations, authentication, and validation.

✅ File System Operations – Reading, writing, and managing files with the fs module.

✅ Real-Time Communication – Using WebSockets (like socket.io) for chat apps or live updates.

✅ Running Background Tasks – Processing queues, sending emails, or handling scheduled jobs.
1. Authentication: Verifies user identities to control access to the system, ensuring
that users are who they claim to be.

2. Authorization: Determines what authenticated users are allowed to do by


managing permissions and access controls.

3. Input Validation: Checks incoming data for correctness, completeness, and


security to prevent malicious data entry and errors.

4. Session Management: Tracks user activity across various requests to maintain


state and manage user-specific settings.

5. API Management: Provides and handles interfaces for applications to interact,


ensuring smooth data exchange and integration.
7. Error Handling: Manages and responds to errors effectively to maintain system
stability and provide useful error messages.

8. Security Measures: Implements protocols to protect data from unauthorized


access and attacks, such as SQL injection and cross-site scripting (XSS).

9. Data Encryption: Secures sensitive information by encrypting data stored in


databases and during transmission.

10. Logging and Monitoring: Keeps records of system activity to diagnose issues
and monitor system health and security.
In short, JavaScript in the browser focuses on user interactions, UI updates, and
frontend logic, while Node.js handles backend operations like databases, servers,
and APIs. 🚀
Setting Up Node.js on Windows

Step 1: Download Node.js


🔹 Go to the official Node.js website 👉 https://nodejs.org/
🔹 Download the LTS (Long-Term Support) version (recommended for stability).
🔹 The installer includes Node.js + npm (Node Package Manager).
Step 2: Install Node.js

🔹 Open the downloaded .msi file.


🔹 Follow the installation wizard:
✔ Click Next → Accept License → Click Next.
✔ Choose installation path (default is fine) → Click Next.
✔ Select "Add to PATH" (important for running Node.js from the terminal).
✔ Click Install and wait for the installation to finish.
Step 3: Verify Installation

After installation, check if Node.js and npm are installed correctly:

1⃣ Open Command Prompt (cmd) or PowerShell


2⃣ Run the following commands:

node -v # Check Node.js version

npm -v # Check npm version

✔ If both commands show version numbers, Node.js is successfully installed! 🎉


Executing first . js file

Step 4: Run Your First Node.js Script


🔹 Create a new file: app.js
🔹 Add this simple code:
console.log("Hello, Node.js is running!");
🔹 Open Command Prompt, navigate to the file location, and run:
node app.js
✔ If you see "Hello, Node.js is running!", your setup is complete! 🚀
Next Steps

🔹 Install a code editor like VS Code for writing Node.js code.


🔹 Learn how to use npm (npm install <package-name>) to install libraries.
🔹 Start building your first Node.js web server using http or Express.js.

🔥 You are now ready to start with Node.js development! 🚀


What is fs in Node.js?

fs stands for File System. It is a built-in module in Node.js that allows us to


interact with the file system (create, read, write, delete files, and more).

Is fs Built-in or External?

✅ Built-in – This means we do not need to install it separately.


✅ Node.js provides fs as part of its core modules, so we can use it directly with
require("fs").
Why Use fs?

The fs module helps Node.js interact with files, such as:

✔ Reading Files – Read text or JSON files.

✔ Writing Files – Create new files or update existing ones.

✔ Deleting Files – Remove unwanted files.

✔ Creating Folders – Manage directories.


What is a Module?

A module in Node.js is just a JavaScript file that contains reusable code.

Modules help organize code into separate files instead of writing everything in one
large file.
Types of Modules in Node.js
👉 There are three types of modules in Node.js:
1⃣ Built-in Modules (Already available in Node.js)
● Examples: fs, http, path, os
● No need to install separately, just use require("moduleName").
2⃣ Third-party Modules (Installed using npm)
● Examples: express, mongoose, lodash
● Need to install using npm install moduleName.
3⃣ Custom Modules (Your own js files)
● Example: A separate file like math.js that exports functions.
● You can import it using require("./math.js").
What is require in Node.js?

🔹 require is a built-in function in Node.js that allows you to import modules


(libraries or files) into your code.

It helps you:
✅ Load built-in Node.js modules (e.g., fs, http)

✅ Import third-party modules (installed via npm)

✅ Require your own custom files (local modules)

Require Syntax: Use require('module') to include built-in or external modules, or other


JavaScript files in your code.
Syntax of fs.writeFile()

fs.writeFile(filename, data, callbackFunction);

Parameters:

1⃣ filename – Name of the file (with extension) to create or overwrite.


2⃣ data – The content to write inside the file.
3⃣ callbackFunction – A function that runs after writing is complete, handling
success or errors.
const fs = require("fs");

✅ require("fs") – Loads the File System (fs) module, which allows Node.js to
handle files.

✅ const fs – Stores the imported module in a variable named fs, so we can use
its methods.
Use fs.writeFile()

fs.writeFile("output.txt", "writing file", (err) => {

✅ fs.writeFile() – A function to create or overwrite a file.

✅ "output.txt" – The name of the file to create or overwrite.

✅ "writing file" – The text that will be written inside the file.

✅ (err) => { ... } – A callback function that executes after the file operation.
path.join

path.join(__dirname, 'crud_fs');

This is a method in Node.js provided by the built-in path module.It is used to


concatenate multiple path segments into a single path, while correctly handling
and normalizing path separators (/ on linux like system and \ on windows).
Explanation:
● __dirname → /Users/yourname/project (if running from project folder).

● 'crud_fs' → The folder you want to reference.

● path.join(__dirname, 'crud_fs') → Result:

○ macOS/Linux: /Users/yourname/project/crud_fs

○ Windows: C:\Users\yourname\project\crud_fs
What is REPL in Node.js?

REPL stands for:

🔹 R → Read (Takes user input)


🔹 E → Evaluate (Executes the input)
🔹 P → Print (Displays the result)
🔹 L → Loop (Waits for new input)

It is an interactive environment where you can run JavaScript code directly in the
terminal without creating a file.
How to Open REPL in Node.js?

1⃣ Open Command Prompt (Windows) or Terminal (Mac/Linux)

2⃣ Type: node

3⃣ Press Enter

4⃣ Now, you can type JavaScript commands and see results immediately!
REPL Features

✅ Mathematical Calculations

✅ Run JavaScript Functions

✅ Work with Variables

✅ Use Multi-line Code (Type .editor for writing multiple lines)

✅ Access Node.js Built-in Modules (like fs, http)


Useful REPL Commands
Why is REPL Useful?

✅ Quickly test JavaScript and Node.js code.

✅ Debug and experiment without creating files.

✅ Learn and practice JavaScript interactively.


What is the path Module in Node.js?

In Node.js, the path module provides utilities for working with file and directory
paths. It's a built-in module, so you don't need to install any external packages to
use it.
💡 Why is it needed?
Different operating systems use different path formats:

● Windows: C:\Users\John\file.txt
● Linux/macOS: /home/john/file.txt

The path module helps handle paths correctly, no matter which OS the server runs on.
__dirname & __filename – Get Current File/Folder Path

console.log(__dirname); // Output: /home/john/project

console.log(__filename); // Output: /home/john/project/server.js

🚀 Why use it?

● Helps find the current script’s directory or filename dynamically.


path.dirname()

path.dirname() is useful when you want to extract the directory path from a file or
folder. If you're working with a file path, __dirname is enough, but if you need a
parent directory, use path.dirname(__dirname).
path.parse()

The path.parse() method in Node.js breaks down a file path into different parts:

● root → The root of the path (e.g., / or C:\)


● dir → The directory path
● base → The filename with extension
● ext → The file extension
● name → The filename without extension
path.extname()

The path.extname() method extracts the file extension from a given file path.

path.basename()

The path.basename() method extracts the file name (including extension) from a
given file path.
Introduction to HTTP Module

📌 The http module in Node.js allows us to create a web server that can handle
HTTP requests and responses. It provides functionalities to handle:

✅ GET – Retrieve data

✅ POST – Send data to the server

✅ PUT – Update data

✅ DELETE – Remove data


How to Import the HTTP Module?

const http = require("http");


Creating a Basic HTTP Server

The http.createServer() method creates an HTTP server.

http.createServer(): The http.createServer() method in Node.js creates an HTTP


server that listens for incoming requests and sends responses. It allows handling
different HTTP methods (GET, POST, PUT, DELETE, etc.) and serves as the
foundation for building APIs or web servers.
Syntax
http.createServer((req, res) => { ... })

● Creates an HTTP server and takes a callback function with req (request) and
res (response) objects.
● req contains information about the client's request.
● res is used to send data back to the client.
Understanding writeHead(), write(), and end() in Node.js HTTP Module

When creating an HTTP server in Node.js using http.createServer(), the response


(res) object has methods to send data back to the client. These methods are:
1⃣ res.writeHead(statusCode, headers)

Purpose: Sets the HTTP status code and response headers before sending data.

Parameters:
● statusCode → HTTP response code (e.g., 200 for success, 404 for Not Found).
● headers (optional) → An object containing key-value pairs of response headers.
res.writeHead(200, { "Content-Type": "text/plain" });

200 → OK (successful request).

"Content-Type": "text/plain" → Specifies that the response is plain text.


2⃣ res.write(data)
Purpose: Sends the response body (actual content) to the client.
Parameters:
● data → The content to be sent (can be a string, buffer, or stream).
res.write("Hello, World!");
This sends "Hello, World!" to the client.
3⃣ res.end([data])
Purpose: Ends the response and optionally sends final data.
Parameters:
● [data] (optional) → The final data to send before closing the connection.
This closes the response.
If we pass a string like res.end("Goodbye!"), it sends "Goodbye!" before closing.
res.end() signals the end of the response and tells the server that all response
data has been sent to the client. After calling res.end(), no more data can be
written to the response.
The listen() method allows the server to listen for incoming requests.

The server.listen() method is used to start an HTTP server and make it listen for
incoming requests.

server.listen(port, callback);
port (Required)

● The port number the server will listen on.


● Example: 3000, 8080, etc.
● If the port is already in use, you'll get an error.

callback (Optional)

● A function that executes after the server starts successfully.


● Usually used to log a message confirming that the server is running.

You might also like