Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Week 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Core Modules in Node.

JS
- Operating System (os) and File System (fs) packages
In Node.js, the os and fs core modules are essential for interacting with the operating system
and the file system, respectively.
Operating System (os) Module
The os module provides utilities to interact with the operating system, useful for getting system-
specific information.
Key Methods:
 os.arch(): Returns the CPU architecture (e.g., 'x64').
 os.platform(): Returns the OS platform (e.g., 'win32', 'darwin', 'linux').
 os.cpus(): Provides details about each CPU core, such as model, speed, and times.
 os.freemem(): Returns available system memory in bytes.
 os.totalmem(): Gives the total memory in bytes.
 os.hostname(): Returns the system’s hostname.
 os.uptime(): Provides system uptime in seconds.
const os = require('os');
console.log(`Platform: ${os.platform()}`);
console.log(`CPU Architecture: ${os.arch()}`);
console.log(`Free Memory: ${os.freemem()} bytes`);

File System (fs) Module


The fs module enables interaction with the file system, allowing you to create, read, update,
and delete files and directories.
Key Methods:
 fs.readFile(path, callback): Reads the content of a file.
 fs.writeFile(path, data, callback): Writes data to a file, creating it if it doesn't exist.
 fs.appendFile(path, data, callback): Appends data to a file, (add new data at the end of
existing data) creating it if it doesn’t exist.
 fs.rename(oldPath, newPath, callback): Renames a file or directory.
 fs.unlink(path, callback): Deletes a file.
 fs.mkdir(path, callback): Creates a directory.
 fs.rmdir(path, callback): Removes a directory (requires it to be empty).
 fs.stat(path, callback): Provides stats about a file (like size, creation date, etc.).

/////////////Coding index.js////////////////////
const fs = require('fs');
// Writing to a file
fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File created and written to.');

// Reading from the file


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(`File contents: ${data}`);
});
});

const os = require('os');
console.log('Platform:' + os.platform());
console.log('CPU Architecture:' + os.arch());
console.log('Free Memory:' + os.freemem() + 'bytes');

const fs = require('fs');
// Writing to a file
fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File created and written to.');

// Reading from the file


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(`File contents: ${data}`);
});
});

Task / Practice:

Importing files in Node.JS using "module.exports"


In Node.js, you can export functionality (variable, functions, objects, classes etc.) from one file
and import it in another using module.exports and require. This allows you to split your code
into separate files or modules, which makes it more manageable and modular.
Step 1: Create a Module with Addition and Subtraction Functions
We’ll make a file called math.js with two functions: one for addition and one for subtraction.
File: math.js
// Define addition and subtraction functions
function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a - b;
}
// Export the functions so we can use them in another file
module.exports = {
add,
subtract,
};

Step 2: Import and Use the Functions in Another File


Now, let’s create a new file, file2.js, where we’ll import these functions and use them.
// Import the math functions from the math.js file
const math = require('./math');

// Use the functions


console.log(math.add(10, 5)); // Output: 15
console.log(math.subtract(10, 5)); // Output: 5

//to show out out in terminal: node or nodemon file2.js

What’s Happening Here?


1. In math.js: We defined two functions (add and subtract) and exported them together as
an object using module.exports.
2. In app.js: We imported this object with require('./math'), and then used math.add and
math.subtract to do the calculations.

ES6 Module
In ES6, you can use export and import functionality (variable, functions, objects, classes etc.)
instead of module.exports and require to organize your code. ES6 modules provide a more
straightforward syntax and are widely used in modern JavaScript environments.
Step 1: Create a Module with Addition and Subtraction Functions
We’ll make a file called math.js with two functions for addition and subtraction, and export
them using the ES6 syntax.

File: math.js
// Define addition and subtraction functions
function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a - b;
}

// Export the functions using ES6 syntax


export { add, subtract };

Step 2: Import and Use the Functions in Another File


In another file, app.js, we’ll import these functions and use them.
File: app.js
// Import the functions from math.js
import { add, subtract } from './math.js';

// Use the functions


console.log(add(10, 5)); // Output: 15
console.log(subtract(10, 5)); // Output: 5

Lodash package
Lodash provides many functions that simplify common programming tasks.
Lodash is a popular JavaScript utility library that helps you write and maintain your code. This
library uses concepts from functional programming to make data manipulation, object handling,
array operations, and many other tasks easier.
Key Features:
 Array Functions: Manipulate arrays easily (e.g., map, filter, reduce).
 Object Functions: Work with objects (e.g., get, set, cloneDeep).
Commonly Used Functions:
 _.map(): Transform each element in an array.
 _.filter(): Get elements that meet a condition.
 _.reduce(): Combine array values into a single value.
 _.get(): Access a value in an object.
 _.set(): Set a value in an object.
 _.cloneDeep(): Create a deep copy of an object.
 _.debounce(): Delay function execution.
 _.throttle(): Limit how often a function runs.
Installation:
npm install lodash

Example Usage:
const _ = require('lodash');

const numbers = [1, 2, 3, 4, 5];

// Filter even numbers


const evens = _.filter(numbers, num => num % 2 === 0);
console.log(evens); // Output: [2, 4]

// Find the maximum number


const maxNumber = _.max(numbers);
console.log(maxNumber); // Output: 5

Introduction to JSON Format


JSON (JavaScript Object Notation) is a lightweight, easy-to-read format for data exchange. It is
commonly used to send data between a server and a web application.
Key Features:
 Text-Based: Easy for humans to read and write.
 Lightweight: Simple and efficient for data transfer.
 Structured: Organizes data in key-value pairs.
JSON Syntax:
Objects: Enclosed in curly braces {}.
{
"name": "Amjad",
"age": 30
}
Arrays: Enclosed in square brackets [].
{
"fruits": ["apple", "banana", "cherry"]
}

Data Types:
 Strings: Enclosed in double quotes (e.g., "Alice").
 Numbers: No quotes (e.g., 30).
 Booleans: true or false.
 Null: Represents empty values.

JSON to JavaScript Object Conversion


To convert a JSON string into a JavaScript object, use JSON.parse():
// JSON string
const jsonString = '{"name": "Ali", "age": 25}';

// Convert JSON to JavaScript object


const jsObject = JSON.parse(jsonString);

// Output the object


console.log(jsObject); // { name: 'Ali', age: 25 }

JavaScript Object to JSON Conversion


To convert a JavaScript object into a JSON string, use JSON.stringify():
// JavaScript object
const jsObject = { name: "Ali", age: 25 };

// Convert JavaScript object to JSON


const jsonString = JSON.stringify(jsObject);

// Output the JSON string


console.log(jsonString); // {"name":"Ali","age":25}
Create a simple API with endpoints for basic operations (GET endpoint to
retrieve a list of items, POST endpoint to add a new item)
const express = require('express')
const app = express() //app is object of express
const port = 3000
app.listen(port, ()=>{
console.log("server is open now")
})

// API WEEK 3
const _= require('lodash') //lodash require
app.use(express.json()) // Informs Node.js that incoming data will be in JSON format (key-value
pairs as an object)
let obj= {} //object created

app.get("/page1", (req, resp)=>{


resp.send("helo helloooo")
})

app.post('/post-data', (req, res)=>{ //rout and call back function, assum login form
_.set(obj, 'item', req.body.itemName) //.set is loadash function used store data in any
object, it has 3 parameters
//1. obj. The data coming from the frontend etc. will be stored in this variable.
//2. Since we are sending data in JSON format, we need to provide a key here, and the data
coming from the frontend will be the value for this key.
// It means that when the user sends the name of the item, this name comes in req.body
under itemName
res.send(obj)
})
//http://localhost:3000/post-data

Test API in postman:


Select method post and provide url
Select body and then raw
Choose json and write key and value like for example:
{
"itemName": "apple"
}

You might also like