Hello World:
console.log("Hello World");
Variables:
const name = "John Doe";
console.log("My name is", name);
Arithmetic Operations:
const num1 = 5;
const num2 = 10;
console.log("Sum:", num1 + num2);
console.log("Difference:", num1 - num2);
console.log("Product:", num1 * num2);
console.log("Quotient:", num1 / num2);
Conditional Statements:
const age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Loops:
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
Functions:
function greet(name) {
console.log("Hello", name);
}
greet("John Doe");
Arrays:
const names = ["John", "Jane", "Jim"];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
Objects:
const person = {
name: "John Doe",
age: 30,
city: "New York"
};
console.log(person.name, person.age, person.city);
Modules:
// greet.js
exports.greet = function(name) {
console.log("Hello", name);
};
// index.js
const greet = require('./greet');
greet.greet("John Doe");
Asynchronous Operations:
const fs = require('fs');
fs.readFile('data.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log("Reading file...");
In this example, the fs.readFile function is used to read a text file asynchronously. The function takes three arguments: the name of the file to read, the encoding of the file, and a callback function that will be called when the file has been read. The console.log statement outside the callback function is executed immediately, before the file has been read, to demonstrate that the file read operation is asynchronous.
This example demonstrates how to perform asynchronous operations in Node.js, which is important for building scalable and performant applications that can handle multiple requests at the same time.