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

Backend-Notes

The document provides an introduction to Node.js, explaining the roles of frontend, backend, and database in web development, and detailing the client-server model. It highlights the significance of Node.js for backend development using JavaScript, its architecture based on the V8 engine, and the CommonJS module system for code organization. Additionally, it includes practical examples of creating and running scripts, utilizing built-in modules, and building a word counter CLI application.

Uploaded by

Ayesha Shaw
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Backend-Notes

The document provides an introduction to Node.js, explaining the roles of frontend, backend, and database in web development, and detailing the client-server model. It highlights the significance of Node.js for backend development using JavaScript, its architecture based on the V8 engine, and the CommonJS module system for code organization. Additionally, it includes practical examples of creating and running scripts, utilizing built-in modules, and building a word counter CLI application.

Uploaded by

Ayesha Shaw
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Introduction to Node.

js
In web development, creating functional applications requires three core components: Frontend, Backend, and
Database. Think of it as a restaurant where the frontend is the menu and waiter, the backend is the kitchen, and the
database is the storage of ingredients.

Frontend

The Frontend is what users interact with directly on a website. It includes all the visuals, layouts, and interfaces that
users can see and click on. This part of the application runs in the browser and is built using HTML, CSS, and
JavaScript.

Backend

The Backend is the “kitchen” of the application. It handles all the behind-the-scenes tasks, like processing user
requests, running the core logic, and communicating with the database. For instance, when you log into a website,
the backend checks your credentials, accesses the database, and sends the appropriate response.

Database

The Database is where data is stored and managed, like storing user profiles, messages, and other necessary
information. In our restaurant analogy, it’s the storage room where all ingredients are kept for quick access.

2. Client-Server Model

The Client-Server Model is a foundational concept in web development. Here’s how it works:

1. Client (Frontend): The client, typically a browser, sends a request to the server, like asking for data to display
on a page.

2. Server (Backend): The server processes this request, runs any required code, retrieves data from the
database, and returns a response.

For example, if you search for a product, the client sends a request to the backend. The backend retrieves relevant
data from the database, processes it, and responds to the client.

 Request: The action the client asks the server to perform, often done through an API.

 Response: The server's answer to the client's request, including the requested data or an error message.

 API Endpoint: A specific address on the backend server where the client sends requests,
like api.website.com/products.

3. The Role of the Backend in Web Applications

The backend is responsible for several crucial functions, including:

 Business Logic: Handling the main functionality, such as calculating prices or processing orders.

 Validation: Ensuring data is accurate, e.g., validating a user’s input on a form.

 Database Access: Storing, retrieving, and managing data.

 Security: Protecting data, managing user authentication, and securing transactions.

 Heavy Computing: Running complex calculations or data-intensive tasks.


4. Backend Development in JavaScript with Node.js

While many languages like Python, Ruby, and Java are popular for backend development, JavaScript has also become
a major player in backend development through Node.js. Unlike the frontend, the backend doesn't have a browser to
execute JavaScript. Node.js acts as a JavaScript runtime, allowing developers to run JavaScript directly on the server.

Why Node.js?

 JavaScript Everywhere: Frontend and backend can both be written in JavaScript, simplifying development.

 Non-Blocking I/O: Node.js handles requests efficiently, making it excellent for scalable, fast applications.

5. The Story of Node.js and the V8 Engine

Node.js was created by Ryan Dahl in 2009 to make server-side JavaScript a reality. It uses Google’s V8 engine, which
is also used in Chrome, to convert JavaScript code into fast, machine-readable code.

The core code of Node.js is open-source and has grown to be a popular choice for backend developers due to its
speed, efficiency, and a vast ecosystem of modules.

6. Creating and Running Simple Scripts in Node.js

Let’s create a simple script to explore Node.js in action:

// greet.js

console.log("Hello, welcome to Node.js!");

To run this script:

1. Save the code as greet.js.

2. Open your terminal, navigate to the file location, and type:

3. node greet.js

4. You’ll see "Hello, welcome to Node.js!" printed in the terminal.

7. The CommonJS Module System

Modules in Node.js help us organize code by splitting it into reusable parts. Node uses CommonJS, which defines
how modules work.

Exporting and Requiring Modules

 Exporting: To make a function or object available in other files, use module.exports.

 Requiring: To use an exported module, use require().

Example:

// square.js

function square(num) {
return num * num;
}
module.exports = square;
// app.js
const square = require('./square');
console.log(square(5)); // Output: 25
8. Node.js Modules Superpowers: npm and Built-in Modules

In addition to custom modules, Node.js provides:

 Built-in Modules: Modules like fs (file system), http, and path.

 npm (Node Package Manager): A vast repository of external modules you can install and use in your
projects.

Using the fs Module

The fs module allows for interaction with the file system, such as reading, writing, or deleting files.

const fs = require('fs');
fs.writeFileSync('message.txt', 'Hello, Node.js!');
console.log('File created successfully');

9. Project: Building a Word Counter CLI Application

Let’s build a simple Command Line Interface (CLI) tool using Node’s fs module to count words in a file.

Step-by-Step Guide

1. Setup: Create a file wordCounter.js.

2. Input from CLI:

 Use process.argv to get file name input from the command line.

3. Read File and Count Words:

 Read the file using fs.readFileSync.

 Split content by whitespace to count words.

4. Display Word Count.

// wordCounter.js
const fs = require('fs');

const fileName = process.argv[2]; // Get file name from CLI argument


if (!fileName) {
console.log('Please provide a file name');
process.exit();
}

try {
const data = fs.readFileSync(fileName, 'utf8');
const wordCount = data.split(/\s+/).length;
console.log(`Word count: ${wordCount}`);
} catch (error) {
console.error('Error reading file:', error.message);
}

To run this script:

1. Create a text file example.txt with some content.

2. Run the command:

3. node wordCounter.js example.txt

4. You’ll see the word count displayed in the terminal.


11. Summary

 The Frontend is the user interface, the Backend processes requests, and the Database stores data.

 The Client-Server Model defines how requests and responses are handled between frontend and backend.

 Node.js allows JavaScript to run server-side, powered by the V8 engine.

 Node’s CommonJS module system and npm provide robust module management.

 Using the fs module, we created a word counter CLI tool.

12. Additional Resources

 Node.js Official Documentation

 JavaScript Modules: A Beginner’s Guide

Backend Development (Class Notes) – Day-01


Web app exist without backend?
No

Client - Server architecture

Backend - Handles business logic, storing and retreiving data, auth etc;

We have to program a computer to do these tasks;

Server - just another computer which is programmed to serve;

^ This programming of the computer/server, can be done in many languages


Java, Rust, C++, Python, Javascript

Javascript <--> Node;

1. Javascript - it was meant only to be run in the browser;


2. ^ there's some engine in the browser which helps run Javascript

HTML, CSS, JS - frontend stack;

Ryan Dhal - why not make JS run outside the browser in a computer;
^ Advantages - JS can be used for full stack - same developer who knows only html, css and js can also
do the backend;

Chrome - v8 engine;
Firefox - spidermonkey;

He took out the (v8 engine + added a few more things as required) to run JS outside the browser;

Node - (v8 engine + added a few more things as required).

Node - Runtime environment which helps run Javascript outside the browser;

//Modules
^ A part of code which is reusable, we can have it in separate file;

//node released in 2009


Export : module.exports = {add, mul, diff, div}
Import : const x = require("y")
^ This way of importing/exporting is known as CJS way;
CJS - common js;

//ES6 feature - 2015


import x from "y"
export default sum;
^ This way of importing/exporting is known as ESM way;
ESM - Ecma script modules

Modules :
1. Custom modules - where we wrote our own code - hello.js, calc.js etc
2. Inbuilt node modules as well

a. go to google, search nodejs docs;


b. explore/go through the list of the inbuilt node modules;
c. tell me which inbuilt node module can probably be used to know my computer's OS information - OS;
// const {div, diff, mul, add} = require("./calc") //importing from our own modules
// const welcome_message = require("./hello")

// console.log(welcome_message)

// const os = require("os") //importing from inbuilt node module;


// console.log(os.version())

//explore a module which is used to read or write files

// const fs = require("fs")

// //to read a file


// const output = fs.readFileSync("./hello.js", {encoding : "utf-8"})
// console.log(output)

//to write to a file


// fs.writeFileSync("./output.txt", "Bye Bye from Node")

// fs.appendFileSync("./output.txt", output)

const process = require("process")


const fs = require("fs")

const filename = process.argv[2]

const output = fs.readFileSync(filename, {encoding : "utf-8"})


console.log(output)

You might also like