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

NodeJs Basics Practice

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

NodeJS Basics Practice

ES6, or ECMAScript 2015, introduced many new features and syntax


enhancements to JavaScript, making the language more powerful and easier to
use. Here's a brief overview of some key ES6 features and the concept of ES6
modules:

Key ES6 Features:


1. Arrow Functions:
Arrow functions provide a shorter syntax for writing functions.

const add = (a, b) => a + b;

2. let and const:


These keywords are used for block-scoped variable declarations.

let x = 10;
const y = 20;

3. Template Literals:
Template literals allow for easier string interpolation.

const name = 'World';


console.log(`Hello, ${name}!`);

4. Destructuring:
Destructuring assignment allows for unpacking values from arrays or
properties from objects into distinct variables.

const [a, b] = [1, 2];


const {name, age} = {name: 'Alice', age: 25};

5. Default Parameters:
Functions can have default values for parameters.

NodeJS Basics Practice 1


function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}

6. Rest and Spread Operators:


The rest operator (
... ) allows for representing an indefinite number of arguments as an array.

The spread operator is used to expand an array into individual elements.

function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}

const arr = [1, 2, 3];


console.log(...arr); // 1 2 3

7. Classes:
ES6 introduced a more straightforward and concise way to create classes and
handle inheritance.

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}

8. Promises:
Promises provide a cleaner way to handle asynchronous operations.

NodeJS Basics Practice 2


const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});

promise.then(result => console.log(result));

ES6 Modules:
ES6 modules allow you to export and import code between different files, making
it easier to organize and maintain your codebase.

Exporting:

// In file `math.js`
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

Importing:

// In file `main.js`
import { add, subtract } from './math.js';

console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2

ES6 modules are now widely supported in modern JavaScript environments,


making it easier to write modular and maintainable code.

If you have specific questions or need examples on any of these features, feel
free to ask!

Asynchronous Programming in Browser vs. Node.js:


Both the browser environment and Node.js support asynchronous programming,
but they do so in slightly different ways due to their different use cases.

NodeJS Basics Practice 3


Browser Environment:
Asynchronous JavaScript: In the browser, asynchronous operations are
crucial for tasks like making network requests (AJAX calls), handling user
interactions, and manipulating the DOM without blocking the main thread.

Common APIs: Common asynchronous APIs in the browser include setTimeout ,


setInterval , fetch , and event listeners (e.g., click , keyup ).

Node.js Environment:
Non-Blocking I/O: Node.js was designed for building scalable network
applications and uses non-blocking I/O operations to handle many
connections simultaneously.

Asynchronous APIs: Node.js provides asynchronous APIs for file system


operations ( fs module), network requests ( http module), and more.

Event-Driven Architecture in Node.js:


Node.js uses an event-driven architecture, which is a key part of its asynchronous
behavior. Here’s how it works:

1. Event Loop: The event loop is a core feature of Node.js that allows it to
perform non-blocking I/O operations. It listens for events and executes the
corresponding callback functions.

The event loop continuously checks for pending tasks (e.g., timers,
network requests, file I/O).

When an asynchronous operation completes, the event loop picks up the


callback and executes it.

2. Events and Callbacks: In Node.js, many APIs are designed to emit events. For
example, the http server emits events when a request is received.

const http = require('http');

const server = http.createServer((req, res) => {


res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');

NodeJS Basics Practice 4


res.end('Hello, World!\\n');
});

server.listen(3000, '127.0.0.1', () => {


console.log('Server running at <http://127.0.0.1:3000/
>');
});

In this example, the createServer method sets up an event listener for incoming
HTTP requests.

3. Event Emitters: Node.js provides an EventEmitter class that allows you to


create and handle custom events.

const EventEmitter = require('events');


const myEmitter = new EventEmitter();

// Register an event listener


myEmitter.on('event', () => {
console.log('An event occurred!');
});

// Emit the event


myEmitter.emit('event');

Relationship Between Event-Driven and Asynchronous Behavior:


Event-Driven: The event-driven nature of Node.js means that the application
flow is determined by events. When an event occurs (e.g., a network request
completes), a corresponding callback function is executed.

Asynchronous: This event-driven approach is inherently asynchronous


because events can happen at any time, and Node.js can handle other tasks
while waiting for events. Asynchronous operations allow Node.js to remain
responsive and handle many connections concurrently.

Summary:

NodeJS Basics Practice 5


Asynchronous Programming: Both the browser and Node.js environments
support asynchronous programming to handle tasks without blocking the main
thread.

Event-Driven Architecture: Node.js's event-driven architecture uses the


event loop and event emitters to handle asynchronous operations efficiently.

Non-Blocking I/O: Node.js uses non-blocking I/O to manage multiple


operations simultaneously, making it well-suited for network applications.

Understanding these concepts helps in building efficient and scalable applications


with Node.js. If you have more questions or need further clarification, feel free to
ask!

1. Getting the Operating System Type:

const os = require('os');

console.log('Operating System Type:', os.type());


// Possible outputs: 'Linux', 'Darwin' (for macOS), 'Windows_
NT'

2. Getting the Platform:

const os = require('os');

console.log('Platform:', os.platform());
// Possible outputs: 'linux', 'darwin', 'win32'

3. Getting the CPU Architecture:

const os = require('os');

NodeJS Basics Practice 6


console.log('CPU Architecture:', os.arch());
// Possible outputs: 'x64', 'arm', 'ia32'

4. Getting CPU Information:

const os = require('os');

const cpus = os.cpus();


console.log('CPU Information:', cpus);
// Outputs an array of objects containing information about e
ach CPU/core

5. Getting Total and Free Memory:

const os = require('os');

console.log('Total Memory:', os.totalmem());


console.log('Free Memory:', os.freemem());
// Outputs total and free memory in bytes

6. Getting Home Directory:

const os = require('os');

console.log('Home Directory:', os.homedir());


// Outputs the path to the home directory

7. Getting Hostname:

const os = require('os');

console.log('Hostname:', os.hostname());
// Outputs the hostname of the operating system

NodeJS Basics Practice 7


8. Getting Network Interfaces:

const os = require('os');

const networkInterfaces = os.networkInterfaces();


console.log('Network Interfaces:', networkInterfaces);
// Outputs an object containing network interfaces and their
details

9. Getting System Uptime:

const os = require('os');

console.log('System Uptime:', os.uptime(), 'seconds');


// Outputs the system uptime in seconds

10. Getting User Information:

const os = require('os');

const userInfo = os.userInfo();


console.log('User Information:', userInfo);
// Outputs an object containing information about the current
user

Example of a Complete Script Using os Module:


Here's a complete script that utilizes multiple methods from the os module to print
out various system information:

const os = require('os');

console.log('Operating System Info:');


console.log('Type:', os.type());
console.log('Platform:', os.platform());

NodeJS Basics Practice 8


console.log('CPU Architecture:', os.arch());
console.log('CPU Info:', os.cpus());
console.log('Total Memory:', os.totalmem());
console.log('Free Memory:', os.freemem());
console.log('Home Directory:', os.homedir());
console.log('Hostname:', os.hostname());
console.log('Network Interfaces:', os.networkInterfaces());
console.log('System Uptime:', os.uptime(), 'seconds');
console.log('User Information:', os.userInfo());

These snippets demonstrate how to use the os module to gather various pieces
of information about the operating system and hardware, which can be very
useful for system monitoring, diagnostics, and optimization tasks.

NodeJS Basics Practice 9

You might also like